orgstar command-line tool !524

merged merged by cmc on 2026-11-27 06:56 UTC · krz/orgstar:174-command-line-tool into main

44 files changed, +2712 −517

One commit's changes, read-only. Review comments go on all commits.

Layout: unified · split

Changed files (44)
Package.swift +8 −2 · view
@@ -26,7 +26,8 @@ let package = Package(
26 .executable(name: "OrgstarShare", targets: ["OrgstarShare"]), 26 .executable(name: "OrgstarShare", targets: ["OrgstarShare"]),
27 .executable(name: "OrgstarWidgets", targets: ["OrgstarWidgets"]), 27 .executable(name: "OrgstarWidgets", targets: ["OrgstarWidgets"]),
28 .executable(name: "OrgstarWatch", targets: ["OrgstarWatch"]), 28 .executable(name: "OrgstarWatch", targets: ["OrgstarWatch"]),
29 .executable(name: "OrgstarWatchWidgets", targets: ["OrgstarWatchWidgets"]) 29 .executable(name: "OrgstarWatchWidgets", targets: ["OrgstarWatchWidgets"]),
30 .executable(name: "OrgstarCLI", targets: ["OrgstarCLI"])
30 ], 31 ],
31 dependencies: [ 32 dependencies: [
32 .package(url: "https://github.com/groue/GRDB.swift", from: "7.11.1"), 33 .package(url: "https://github.com/groue/GRDB.swift", from: "7.11.1"),
@@ -88,7 +89,9 @@ let package = Package(
88 ] 89 ]
89 ), 90 ),
90 .executableTarget(name: "OrgstarSpike", dependencies: ["OrgEditorAppKit"]), 91 .executableTarget(name: "OrgstarSpike", dependencies: ["OrgEditorAppKit"]),
91 .target(name: "OrgApp", dependencies: ["OrgWorkspace", "OrgDocument", "OrgPresentation", "OrgWatchData"]), 92 // Settings and the configuration files, without UI: the apps and the command-line tool read them.
93 .target(name: "OrgConfig", dependencies: ["OrgCore", "OrgWorkspace"]),
94 .target(name: "OrgApp", dependencies: ["OrgConfig", "OrgWorkspace", "OrgDocument", "OrgPresentation", "OrgWatchData"]),
92 // MathJax for PDF export, the dot and mermaid libraries, Pyodide, and reveal.js for slides, which need no network; the apps link it, extensions don't. 95 // MathJax for PDF export, the dot and mermaid libraries, Pyodide, and reveal.js for slides, which need no network; the apps link it, extensions don't.
93 .target(name: "OrgMathJax", resources: [.copy("MathJax"), .copy("Diagrams"), .copy("Pyodide"), .copy("Reveal")]), 96 .target(name: "OrgMathJax", resources: [.copy("MathJax"), .copy("Diagrams"), .copy("Pyodide"), .copy("Reveal")]),
94 // What the phone and the watch send each other; Foundation only, so the watch builds it. 97 // What the phone and the watch send each other; Foundation only, so the watch builds it.
@@ -109,6 +112,9 @@ let package = Package(
109 // The Mac's widget extension, bundled into the app by scripts/build-app.sh; the iOS one 112 // The Mac's widget extension, bundled into the app by scripts/build-app.sh; the iOS one
110 // is built from the same sources by ios/Orgstar.xcodeproj. 113 // is built from the same sources by ios/Orgstar.xcodeproj.
111 .executableTarget(name: "OrgstarWidgets", dependencies: ["OrgApp"]), 114 .executableTarget(name: "OrgstarWidgets", dependencies: ["OrgApp"]),
115 // The `orgstar` command, bundled into the download app's Contents/Helpers by scripts/build-app.sh.
116 .executableTarget(name: "OrgstarCLI", dependencies: ["OrgConfig", "OrgDocument"]),
117 .testTarget(name: "OrgstarCLITests", dependencies: ["OrgstarCLI", "OrgConfig", "OrgDocument"]),
112 .testTarget(name: "OrgCoreTests", dependencies: ["OrgCore"], exclude: ["Conformance"]), 118 .testTarget(name: "OrgCoreTests", dependencies: ["OrgCore"], exclude: ["Conformance"]),
113 .testTarget(name: "OrgDocumentTests", dependencies: ["OrgDocument"]), 119 .testTarget(name: "OrgDocumentTests", dependencies: ["OrgDocument"]),
114 .testTarget(name: "OrgWatchDataTests", dependencies: ["OrgWatchData"]), 120 .testTarget(name: "OrgWatchDataTests", dependencies: ["OrgWatchData"]),
Sources/OrgApp/AgendaFiles.swift +1 −43 · view
@@ -1,47 +1,5 @@
1import Foundation 1import Foundation
2import OrgCore 2import OrgConfig
3
4/// `org-agenda-files` as the `(org-agenda-files)` function reads it: each entry a folder (its
5/// `.org` files not starting with a dot, in name order, not below it), an `.org` file, or a
6/// file listing more entries one per line, as the variable's string form names one.
7/// Relative paths count from `base`, standing in for `org-directory`. Missing files are left out.
8public enum AgendaFiles {
9 public static func resolve(_ entries: [String], base: String?, fileManager: FileManager = .default) -> [String] {
10 var out: [String] = []
11 var seen: Set<String> = []
12 func expand(_ entry: String, from base: String?) -> String {
13 let path = OrgPaths.expandingTilde(entry)
14 if path.hasPrefix("/") || base == nil { return (path as NSString).standardizingPath }
15 return ((base! as NSString).appendingPathComponent(path) as NSString).standardizingPath
16 }
17 func add(_ path: String) {
18 if seen.insert(path).inserted { out.append(path) }
19 }
20 func visit(_ entry: String, listed: Bool) {
21 let path = expand(entry, from: base)
22 var isDirectory: ObjCBool = false
23 guard fileManager.fileExists(atPath: path, isDirectory: &isDirectory) else { return }
24 if isDirectory.boolValue {
25 let names = (try? fileManager.contentsOfDirectory(atPath: path)) ?? []
26 for name in names.sorted() where !name.hasPrefix(".") && name.hasSuffix(".org") {
27 let file = (path as NSString).appendingPathComponent(name)
28 var dir: ObjCBool = false
29 if fileManager.fileExists(atPath: file, isDirectory: &dir), !dir.boolValue { add(file) }
30 }
31 } else if path.hasSuffix(".org") || listed {
32 add(path)
33 } else if let text = try? String(contentsOfFile: path, encoding: .utf8) {
34 // `org-read-agenda-file-list`.
35 for line in text.components(separatedBy: .newlines) {
36 let trimmed = line.trimmingCharacters(in: .whitespaces)
37 if !trimmed.isEmpty { visit(trimmed, listed: true) }
38 }
39 }
40 }
41 for entry in entries { visit(entry, listed: false) }
42 return out
43 }
44}
45 3
46extension WorkspaceModel { 4extension WorkspaceModel {
47 /// `(org-agenda-files)`: `list` resolved, or when it is empty the org files at the top of 5 /// `(org-agenda-files)`: `list` resolved, or when it is empty the org files at the top of
Sources/OrgApp/AgendaModel.swift +14 · view
@@ -4,6 +4,20 @@ import OrgCore
4import OrgIndex 4import OrgIndex
5import OrgPresentation 5import OrgPresentation
6 6
7/// What one view of a block agenda shows.
8public struct AgendaBlockResult: Equatable, Sendable {
9 public let header: String
10 public let mode: AgendaMode
11 public var days: [AgendaDay] = []
12 public var list: [AgendaItem] = []
13 public var events: [AgendaEvent] = []
14
15 public var isAgenda: Bool {
16 if case .agenda = mode { return true }
17 return false
18 }
19}
20
7/// Parsed agenda files by path, kept while the file's modification date and size and the 21/// Parsed agenda files by path, kept while the file's modification date and size and the
8/// settings it was parsed with hold. Agenda models over one workspace can share one. 22/// settings it was parsed with hold. Agenda models over one workspace can share one.
9@MainActor 23@MainActor
Sources/OrgApp/CaptureModel.swift +2 −177 · view
@@ -1,156 +1,9 @@
1import Foundation 1import Foundation
2import Observation 2import Observation
3import OrgConfig
3import OrgCore 4import OrgCore
4import OrgDocument 5import OrgDocument
5 6
6/// Capture templates from `capture.toml`, and capturing into their targets:
7///
8/// ```toml
9/// [[template]]
10/// key = "t"
11/// name = "Personal todo"
12/// type = "entry" # entry, item, checkitem, plain or table-line
13/// file = "todo.org" # relative to the first folder, or ~/… or /…
14/// headline = "Inbox" # or olp = "Projects/Work"; neither for the end of the file
15/// template = "* TODO %?\n%i\n%a"
16/// prepend = false
17/// ```
18///
19/// Other targets: `datetree = true` (under `olp` if given; `tree-type` "day", "week",
20/// "month", or groups such as "year quarter month"), `regexp = "…"` with `file`,
21/// `id = "…"` without `file`, `clock = true` without `file`. Other properties, as in
22/// `org-capture-templates`: `immediate-finish`, `empty-lines`, `empty-lines-before`,
23/// `empty-lines-after`, `jump-to-captured`, `clock-in`, `clock-keep`, `clock-resume`,
24/// `table-line-pos`, `time-prompt`.
25///
26/// A `[[template]]` with only `key` and `name` is a group: the templates whose keys start
27/// with its key are listed under it.
28@MainActor
29public enum CaptureTemplates {
30 public static var userFile: URL { UserConfig.file("capture.toml") }
31
32 /// The templates in your Doom configuration.
33 public static let defaults = [
34 CaptureTemplate(key: "t", name: "Personal todo", target: .headline(file: "todo.org", headline: "Inbox"), template: "* TODO %?\n%i\n%a"),
35 CaptureTemplate(key: "n", name: "Personal notes", target: .headline(file: "notes.org", headline: "Inbox"), template: "* %u %?\n%i\n%a"),
36 ]
37
38 public static func load(userFile: URL = userFile) -> (templates: [CaptureTemplate], groups: [CaptureGroup], problems: [String]) {
39 guard let text = try? String(contentsOf: userFile, encoding: .utf8) else { return (defaults, [], []) }
40 let tables: [TOML.Table]
41 do {
42 tables = try TOML.parse(text)
43 } catch {
44 return (defaults, [], ["capture.toml: \(error)"])
45 }
46 var templates: [CaptureTemplate] = []
47 var groups: [CaptureGroup] = []
48 var problems: [String] = []
49 for table in tables where !(table.name.isEmpty && table.values.isEmpty) && RoamTemplate.Set(rawValue: table.name) == nil {
50 guard table.name == "template", table.isArrayElement else {
51 problems.append("capture.toml line \(table.line): expected [[template]]")
52 continue
53 }
54 let values = table.values
55 if let key = values["key"]?.string, let name = values["name"]?.string, values.count == 2 {
56 groups.append(CaptureGroup(key: key, name: name))
57 continue
58 }
59 let fileless = values["id"]?.string != nil || values["clock"]?.bool == true || values["denote"]?.bool == true
60 guard let key = values["key"]?.string, let body = values["template"]?.string, let file = values["file"]?.string ?? (fileless ? "" : nil) else {
61 problems.append("capture.toml line \(table.line): a template needs key, file and template")
62 continue
63 }
64 guard let kind = CaptureTemplate.Kind(rawValue: table.values["type"]?.string ?? "entry") else {
65 problems.append("capture.toml line \(table.line): unknown type")
66 continue
67 }
68 let olp = values["olp"]?.string.map { $0.split(separator: "/").map(String.init) }
69 let target: CaptureTemplate.Target
70 if let id = values["id"]?.string {
71 target = .id(id)
72 } else if values["clock"]?.bool == true {
73 target = .clock
74 } else if values["datetree"]?.bool == true {
75 guard let tree = CaptureTemplate.TreeType(rawValue: values["tree-type"]?.string ?? "day") else {
76 problems.append("capture.toml line \(table.line): tree-type is day, week, month, or some of year, quarter, month, week and day")
77 continue
78 }
79 target = .datetree(file: file, path: olp ?? [], tree: tree)
80 } else if let regexp = values["regexp"]?.string {
81 target = .regexp(file: file, regexp: regexp)
82 } else if let headline = values["headline"]?.string {
83 target = .headline(file: file, headline: headline)
84 } else if let olp {
85 target = .outline(file: file, path: olp)
86 } else {
87 target = .file(file)
88 }
89 templates.append(CaptureTemplate(key: key, name: values["name"]?.string ?? key, kind: kind, target: target, template: body, options: options(values)))
90 }
91 return (templates.isEmpty ? defaults : templates, templates.isEmpty ? [] : groups, problems)
92 }
93
94 /// A table's template properties beyond the target.
95 nonisolated static func options(_ values: [String: TOML.Value]) -> CaptureTemplate.Options {
96 func flag(_ name: String) -> Bool { values[name]?.bool ?? false }
97 func lines(_ name: String) -> Int? { values[name]?.integer }
98 return CaptureTemplate.Options(
99 prepend: flag("prepend"), immediateFinish: flag("immediate-finish"), emptyLines: lines("empty-lines"),
100 emptyLinesBefore: lines("empty-lines-before"), emptyLinesAfter: lines("empty-lines-after"),
101 jumpToCaptured: flag("jump-to-captured"), clockIn: flag("clock-in"), clockKeep: flag("clock-keep"), clockResume: flag("clock-resume"),
102 tableLinePos: values["table-line-pos"]?.string, timePrompt: flag("time-prompt"), denote: flag("denote")
103 )
104 }
105
106 /// What `org-capture` lists after the keys typed so far: the groups and templates one key
107 /// longer, in the templates' order. A template with no group for its prefix is listed
108 /// too, so that it can be reached.
109 public static func menu(_ templates: [CaptureTemplate], groups: [CaptureGroup], typed: String) -> [CaptureMenuItem] {
110 let depth = typed.count + 1
111 var items: [CaptureMenuItem] = []
112 var shown: Set<String> = []
113 for template in templates where template.key.hasPrefix(typed) {
114 if template.key.count > depth, let group = groups.first(where: { $0.key == String(template.key.prefix(depth)) }) {
115 if shown.insert(group.key).inserted { items.append(.group(group)) }
116 } else {
117 items.append(.template(template))
118 }
119 }
120 for group in groups where group.key.hasPrefix(typed) && group.key.count == depth && !shown.contains(group.key) { items.append(.group(group)) }
121 return items
122 }
123
124 /// The template's name after the names of the groups above it: `Work › Meeting`.
125 public static func label(_ template: CaptureTemplate, groups: [CaptureGroup]) -> String {
126 let names = (1..<max(1, template.key.count)).compactMap { n in groups.first { $0.key == String(template.key.prefix(n)) }?.name }
127 return (names + [template.name]).joined(separator: " › ")
128 }
129}
130
131/// A key and a description with no template: `("w" "Work")` in `org-capture-templates`.
132public struct CaptureGroup: Sendable, Equatable, Identifiable {
133 public let key: String
134 public let name: String
135 public var id: String { key }
136 public init(key: String, name: String) {
137 self.key = key
138 self.name = name
139 }
140}
141
142public enum CaptureMenuItem: Identifiable {
143 case group(CaptureGroup)
144 case template(CaptureTemplate)
145 public var key: String {
146 switch self {
147 case .group(let g): g.key
148 case .template(let t): t.key
149 }
150 }
151 public var id: String { key }
152}
153
154extension DocumentSession { 7extension DocumentSession {
155 /// Places captured `text` with `template`: through the buffer when the target is open, 8 /// Places captured `text` with `template`: through the buffer when the target is open,
156 /// otherwise in the file, created if missing, through the save path. `id` and `clock` 9 /// otherwise in the file, created if missing, through the save path. `id` and `clock`
@@ -175,9 +28,7 @@ extension DocumentSession {
175 28
176 /// A template's file: absolute, `~/…`, or relative to `root`. 29 /// A template's file: absolute, `~/…`, or relative to `root`.
177 public static func resolve(_ file: String, root: String?) -> String { 30 public static func resolve(_ file: String, root: String?) -> String {
178 if file.hasPrefix("/") { return file } 31 CaptureTemplates.path(file, root: root)
179 if file.hasPrefix("~") { return OrgPaths.expandingTilde(file) }
180 return ((root ?? OrgPaths.home) as NSString).appendingPathComponent(file)
181 } 32 }
182 33
183 /// `%a`: a link to the heading at the caret, as `org-store-link` makes one. 34 /// `%a`: a link to the heading at the caret, as `org-store-link` makes one.
@@ -189,37 +40,11 @@ extension DocumentSession {
189 } 40 }
190} 41}
191 42
192extension CaptureContext {
193 /// `%[file]` reads the file, a relative path from the configuration folder.
194 public mutating func readsTemplateFiles(from directory: URL = UserConfig.directory) {
195 self.directory = directory.path
196 readFile = { try? String(contentsOfFile: $0, encoding: .utf8) }
197 }
198}
199
200public struct CaptureError: Error, Equatable { 43public struct CaptureError: Error, Equatable {
201 public let message: String 44 public let message: String
202 public init(message: String) { self.message = message } 45 public init(message: String) { self.message = message }
203} 46}
204 47
205/// The edit `Capture.place` makes, as a command so the save path applies it. The selection
206/// it leaves is the captured entry's start.
207struct CapturePlacement: OrgCommand {
208 let text: String
209 let template: CaptureTemplate
210 var id: String { "internal.capture" }
211 var title: String { "Capture" }
212 func applies(in context: EditContext) -> Bool { true }
213 func run(in context: EditContext) -> CommandStep {
214 switch Capture.placement(text, template: template, in: context.text, settings: context.tree.settings, now: context.now, calendar: context.calendar) {
215 case .failure(.message(let message)):
216 return .failed(message)
217 case .success(let placed):
218 return .commit(EditResult(baseRevision: context.revision, edits: TextEdit.between(context.text, placed.text), selection: [placed.start..<placed.start]))
219 }
220 }
221}
222
223extension DocumentSession { 48extension DocumentSession {
224 /// Shortcuts' "Capture to Orgstar": `text` as `%i` in the template keyed `key` (the first 49 /// Shortcuts' "Capture to Orgstar": `text` as `%i` in the template keyed `key` (the first
225 /// when nil or empty), its prompts taking their defaults, filed without the capture window. 50 /// when nil or empty), its prompts taking their defaults, filed without the capture window.
Sources/OrgApp/ClockModel.swift +9 −6 · view
@@ -488,16 +488,17 @@ public final class ClockModel {
488 488
489 /// Brings the running clock in line with the open `CLOCK:` lines of `paths`, so that a 489 /// Brings the running clock in line with the open `CLOCK:` lines of `paths`, so that a
490 /// clock started or stopped in Emacs, or on another device, is the one orgstar knows: the 490 /// clock started or stopped in Emacs, or on another device, is the one orgstar knows: the
491 /// running clock ends when its line was closed or removed, and with none running, the most 491 /// running clock ends when its line was closed or removed, and then or with none running,
492 /// recently started of the open clocks not seen before becomes the running one. Others stay 492 /// the most recently started of the open clocks not seen before (and not started before the
493 /// dangling, for `org-resolve-clocks` at the next clock in. Returns a message when 493 /// one that ended) becomes the running one. Others stay dangling, for `org-resolve-clocks`
494 /// something changed. 494 /// at the next clock in. Returns a message when something changed.
495 @discardableResult 495 @discardableResult
496 public func sync(_ session: DocumentSession, paths: [String]) -> String? { 496 public func sync(_ session: DocumentSession, paths: [String]) -> String? {
497 guard !isResolving else { return nil } 497 guard !isResolving else { return nil }
498 let open = openClocks(session, paths: paths) 498 let open = openClocks(session, paths: paths)
499 let fresh = open.filter { !seenOpen.contains($0.path + "\u{0}" + $0.start) } 499 let fresh = open.filter { !seenOpen.contains($0.path + "\u{0}" + $0.start) }
500 seenOpen.formUnion(open.map { $0.path + "\u{0}" + $0.start }) 500 seenOpen.formUnion(open.map { $0.path + "\u{0}" + $0.start })
501 var stopped: (message: String, startedAt: Date)?
501 if let running { 502 if let running {
502 guard paths.contains(running.path) || session.openDocuments.contains(where: { $0.path == running.path }) else { return nil } 503 guard paths.contains(running.path) || session.openDocuments.contains(where: { $0.path == running.path }) else { return nil }
503 // Its line was closed or removed elsewhere; a file that can't be read says nothing. 504 // Its line was closed or removed elsewhere; a file that can't be read says nothing.
@@ -506,9 +507,11 @@ public final class ClockModel {
506 self.running = nil 507 self.running = nil
507 watched = nil 508 watched = nil
508 save() 509 save()
509 return "The clock in \"\(running.heading)\" was stopped elsewhere" 510 stopped = ("The clock in \"\(running.heading)\" was stopped elsewhere", running.startedAt)
510 } 511 }
511 guard let newest = fresh.max(by: { $0.startedAt < $1.startedAt }) else { return nil } 512 // A clock in another entry started elsewhere as that one stopped, as clocking in there does.
513 let started = fresh.filter { clock in stopped.map { clock.startedAt >= $0.startedAt } ?? true }
514 guard let newest = started.max(by: { $0.startedAt < $1.startedAt }) else { return stopped?.message }
512 running = Running(path: newest.path, start: newest.start, heading: newest.heading, startedAt: newest.startedAt) 515 running = Running(path: newest.path, start: newest.start, heading: newest.heading, startedAt: newest.startedAt)
513 if let text = Self.text(newest.path, session), case let offset = (text as NSString).range(of: "CLOCK: [\(newest.start)]").location, offset != NSNotFound { 516 if let text = Self.text(newest.path, session), case let offset = (text as NSString).range(of: "CLOCK: [\(newest.start)]").location, offset != NSNotFound {
514 let heading = DocumentModel(tree: OrgParser.parse(text)).headings.last { $0.headingRange.lowerBound <= offset }?.headingRange.lowerBound 517 let heading = DocumentModel(tree: OrgParser.parse(text)).headings.last { $0.headingRange.lowerBound <= offset }?.headingRange.lowerBound
Sources/OrgApp/Exports.swift added +2 · view
@@ -0,0 +1,2 @@
1// Modules that import OrgApp see the settings and configuration types too.
2@_exported import OrgConfig
Sources/OrgApp/OrgPreferencesApp.swift added +28 · view
@@ -0,0 +1,28 @@
1import Foundation
2import OrgConfig
3import OrgPresentation
4
5extension OrgPreferences {
6 /// `colors` with the type settings of `[theme]`: font, size, line spacing, heading step.
7 public static func theme(_ colors: ThemeSpec, _ defaults: UserDefaults = .standard) -> ThemeSpec {
8 var spec = colors
9 spec.font = string("themeFont", defaults)
10 spec.bodyFont = string("themeBodyFont", defaults)
11 spec.fontSize = integer("themeFontSize", defaults)
12 spec.lineSpacing = integer("themeLineSpacing", defaults)
13 spec.textWidth = integer("themeTextWidth", defaults)
14 spec.headingSizeStep = integer("themeHeadingStep", defaults)
15 return spec
16 }
17
18 /// `pdf-margin`, `pdf-font` and `pdf-page-numbers`.
19 @MainActor
20 public static func pdfOptions(_ defaults: UserDefaults = .standard) -> PDFExport.Options {
21 PDFExport.Options(margin: integer("pdfMargin", defaults), font: string("pdfFont", defaults), pageNumbers: bool("pdfPageNumbers", defaults))
22 }
23
24 /// `org-yank-dnd-method`.
25 public static func yankDndMethod(_ defaults: UserDefaults = .standard) -> ImageYank.DropMethod {
26 ImageYank.DropMethod(rawValue: string("yankDndMethod", defaults)) ?? .ask
27 }
28}
Sources/OrgApp/RefileTargets.swift +1 −132 · view
@@ -4,125 +4,7 @@ import OrgDocument
4import OrgIndex 4import OrgIndex
5import OrgPresentation 5import OrgPresentation
6 6
7/// `org-refile-targets`, `org-refile-use-outline-path` and 7extension RefileSettings {
8/// `org-refile-allow-creating-parent-nodes` (Org 9.8.7).
9public struct RefileSettings: Sendable, Equatable {
10 /// Where an `org-refile-targets` entry looks.
11 public enum Files: Sendable, Equatable {
12 /// `nil`: the file refiled from.
13 case current
14 case agendaFiles
15 case paths([String])
16 /// Every org file in the folders: orgstar's default.
17 case workspace
18 }
19
20 /// Which headings an entry offers.
21 public enum Spec: Sendable, Equatable {
22 /// `t`: every heading.
23 case all
24 case tag(String), todo(String)
25 /// An Emacs regexp.
26 case regexp(String)
27 case level(Int), maxLevel(Int)
28 }
29
30 public struct Target: Sendable, Equatable {
31 public var files: Files
32 public var spec: Spec
33
34 public init(files: Files, spec: Spec) {
35 self.files = files
36 self.spec = spec
37 }
38 }
39
40 public enum OutlinePath: String, Sendable, CaseIterable {
41 case none = "nil", full = "t", file, fullFilePath = "full-file-path", bufferName = "buffer-name", title
42 }
43
44 public enum Creating: String, Sendable, CaseIterable {
45 case no = "nil", yes = "t", confirm
46 }
47
48 public enum Failure: Error, Equatable {
49 case message(String)
50 }
51
52 public var targets: [Target]
53 public var outlinePath: OutlinePath
54 public var creating: Creating
55
56 /// Headings down to level 3 in every file, as orgstar offers with no `org-refile-targets`.
57 public static let workspaceTargets = [Target(files: .workspace, spec: .maxLevel(3))]
58
59 public init(targets: [Target] = workspaceTargets, outlinePath: OutlinePath = .file, creating: Creating = .no) {
60 self.targets = targets
61 self.outlinePath = outlinePath
62 self.creating = creating
63 }
64
65 /// An `org-refile-targets` value as Lisp writes it: `((nil :maxlevel . 3)
66 /// (org-agenda-files :tag . "project") ("~/notes/x.org" :level . 1))`. Empty text is
67 /// orgstar's default.
68 public static func parseTargets(_ text: String) -> Result<[Target], Failure> {
69 guard text.contains(where: { !$0.isWhitespace }) else { return .success(workspaceTargets) }
70 let value: Sexp
71 do {
72 guard let form = try LispReader.read(text).first?.sexp else { return .success(workspaceTargets) }
73 value = form
74 } catch {
75 return .failure(.message("can't read \(text)"))
76 }
77 func unquote(_ s: Sexp) -> Sexp {
78 if case .list(let items) = s, items.count == 2, items[0].symbol == "quote" { return items[1] }
79 return s
80 }
81 guard let entries = unquote(value).elements else { return .failure(.message("not a list of targets")) }
82 var targets: [Target] = []
83 for entry in entries {
84 // `(FILES . (KEY . VALUE))`, read as `(FILES KEY . VALUE)`, or `(FILES KEY VALUE)`.
85 let head: Sexp
86 var key: String?
87 var argument: Sexp?
88 switch entry {
89 case .dotted(let items, let last) where items.count == 2:
90 head = items[0]
91 key = items[1].symbol
92 argument = last
93 case .list(let items) where items.count == 3:
94 head = items[0]
95 key = items[1].symbol
96 argument = items[2]
97 case .dotted(let items, let last) where items.count == 1 && last.symbol == "t":
98 head = items[0]
99 key = "t"
100 default:
101 return .failure(.message("\(entry.description) isn't a target"))
102 }
103 let files: Files
104 switch head {
105 case .symbol("nil"): files = .current
106 case .symbol("org-agenda-files"): files = .agendaFiles
107 case .string(let path): files = .paths([path])
108 case .list(let items) where items.allSatisfy({ $0.string != nil }): files = .paths(items.compactMap(\.string))
109 default: return .failure(.message("files \(head.description) aren't supported"))
110 }
111 let spec: Spec
112 switch (key, argument) {
113 case ("t"?, _): spec = .all
114 case (":tag"?, .string(let s)?): spec = .tag(s)
115 case (":todo"?, .string(let s)?): spec = .todo(s)
116 case (":regexp"?, .string(let s)?): spec = .regexp(s)
117 case (":level"?, .integer(let n)?): spec = .level(n)
118 case (":maxlevel"?, .integer(let n)?): spec = .maxLevel(n)
119 default: return .failure(.message("\(entry.description) isn't a target"))
120 }
121 targets.append(Target(files: files, spec: spec))
122 }
123 return .success(targets)
124 }
125
126 /// For an answer that isn't a target, `parent/child` with `parent` one: the target and the 8 /// For an answer that isn't a target, `parent/child` with `parent` one: the target and the
127 /// new heading's title, as `org-refile-get-location` splits it. 9 /// new heading's title, as `org-refile-get-location` splits it.
128 public static func newNode(_ answer: String, in targets: [RefileTarget]) -> (parent: RefileTarget, child: String)? { 10 public static func newNode(_ answer: String, in targets: [RefileTarget]) -> (parent: RefileTarget, child: String)? {
@@ -132,19 +14,6 @@ public struct RefileSettings: Sendable, Equatable {
132 guard !child.isEmpty, let target = targets.first(where: { $0.label == parent }) else { return nil } 14 guard !child.isEmpty, let target = targets.first(where: { $0.label == parent }) else { return nil }
133 return (target, child) 15 return (target, child)
134 } 16 }
135
136 /// `org-refile-get-targets`'s `descre` for `spec`, in Emacs syntax.
137 static func regexp(_ spec: Spec) -> String {
138 func quote(_ s: String) -> String { s.map { "[*.\\?+^$".contains($0) ? "\\" + String($0) : String($0) }.joined() }
139 switch spec {
140 case .all: return "^\\*+[ \t]"
141 case .tag(let tag): return "^\\*+[ \t]+.*?:" + quote(tag) + ":"
142 case .todo(let keyword): return "^\\*+[ \t]+" + quote(keyword) + "[ \t]"
143 case .regexp(let re): return re
144 case .level(let n): return "^\\*\\{\(n)\\}[ \t]"
145 case .maxLevel(let n): return "^\\*\\{1,\(n)\\}[ \t]"
146 }
147 }
148} 17}
149 18
150extension WorkspaceModel { 19extension WorkspaceModel {
Sources/OrgApp/TangleWriter.swift +1 −59 · view
@@ -1,65 +1,7 @@
1import Foundation 1import Foundation
2import OrgConfig
2import OrgCore 3import OrgCore
3 4
4/// Writes what `Tangle.run` produced, as `org-babel-tangle` does: a file whose contents
5/// haven't changed is left alone, `:mkdirp` makes its folder, a read-only file is replaced,
6/// and the mode is set after writing. A mode that can't be set doesn't stop the others.
7public enum TangleWriter {
8 public struct Failure: Error, Equatable {
9 public let message: String
10 }
11
12 /// The paths written or already up to date, in order.
13 @discardableResult
14 public static func write(_ output: Tangle.Output, source: String) throws(Failure) -> [String] {
15 let manager = FileManager.default
16 var paths: [String] = []
17 var modeFailure: Failure?
18 for file in output.files {
19 let url = URL(fileURLWithPath: file.path)
20 let data = Data(file.contents.utf8)
21 if let existing = manager.contents(atPath: file.path), existing == data {
22 paths.append(file.path)
23 continue
24 }
25 if (file.path as NSString).standardizingPath == (source as NSString).standardizingPath {
26 throw Failure(message: "Not allowed to tangle into the same file as self")
27 }
28 let folder = url.deletingLastPathComponent()
29 if file.makeDirectories {
30 do {
31 try manager.createDirectory(at: folder, withIntermediateDirectories: true)
32 } catch {
33 throw Failure(message: "Can't make \(folder.path): \(error.localizedDescription)")
34 }
35 }
36 if manager.fileExists(atPath: file.path), !manager.isWritableFile(atPath: file.path) {
37 try? manager.removeItem(at: url)
38 }
39 do {
40 try data.write(to: url)
41 } catch {
42 throw Failure(message: "Can't write \(file.path): \(error.localizedDescription)")
43 }
44 if let mode = file.mode {
45 do {
46 try manager.setAttributes([.posixPermissions: mode], ofItemAtPath: file.path)
47 } catch {
48 modeFailure = modeFailure ?? Failure(message: "\(message(output, source: source)), but can't set the mode of \(file.path): \(error.localizedDescription)")
49 }
50 }
51 paths.append(file.path)
52 }
53 if let modeFailure { throw modeFailure }
54 return paths
55 }
56
57 /// `org-babel-tangle`'s message.
58 public static func message(_ output: Tangle.Output, source: String) -> String {
59 "Tangled \(output.blocks) code block\(output.blocks == 1 ? "" : "s") from \((source as NSString).lastPathComponent)"
60 }
61}
62
63extension DocumentSession { 5extension DocumentSession {
64 /// The files `tangle` would write. 6 /// The files `tangle` would write.
65 public func tangleFiles(_ scope: Tangle.Scope) -> [String] { 7 public func tangleFiles(_ scope: Tangle.Scope) -> [String] {
Sources/OrgApp/UserConfigTheme.swift added +44 · view
@@ -0,0 +1,44 @@
1import Foundation
2import OrgConfig
3import OrgCore
4import OrgPresentation
5
6extension UserConfig {
7 /// The theme `config.toml` (`text`) sets: its `[theme]` tables' colors over those of
8 /// `theme-file` (a path relative to `folder`), over the palettes `light-theme` and
9 /// `dark-theme` name; with problems in all three. Nil when `text` isn't TOML.
10 public static func theme(
11 config text: String, themeFile name: String?, lightTheme: String? = nil, darkTheme: String? = nil, in folder: URL,
12 read: (URL) -> String? = { try? String(contentsOf: $0, encoding: .utf8) }
13 ) -> (theme: ThemeSpec, problems: [String])? {
14 guard let tables = try? TOML.parse(text) else { return nil }
15 var (spec, problems) = ThemeSpec.base(light: lightTheme, dark: darkTheme)
16 if let name, !name.isEmpty {
17 if let themeText = read(folder.appendingPathComponent(name)) {
18 do {
19 let (read, more) = ThemeSpec.reading(try TOML.parse(themeText), over: spec, file: name)
20 spec = read
21 problems += more
22 } catch {
23 problems.append("\(name): \(error)")
24 }
25 } else {
26 problems.append("config.toml: theme-file \(name) can't be read")
27 }
28 }
29 let (merged, more) = ThemeSpec.reading(tables, over: spec)
30 return (merged, problems + more)
31 }
32
33 /// The file Copy to Config Folder writes.
34 public static let copiedThemeFile = "my-theme.toml"
35
36 /// Writes the two palettes into `folder` as `copiedThemeFile`; false, writing nothing, when
37 /// the file is already there.
38 public static func copyTheme(light: Palette, dark: Palette, to folder: URL) throws -> Bool {
39 let file = folder.appendingPathComponent(copiedThemeFile)
40 guard !FileManager.default.fileExists(atPath: file.path) else { return false }
41 try ThemeSpec.themeFile(light: light, dark: dark).write(to: file, atomically: true, encoding: .utf8)
42 return true
43 }
44}
Sources/OrgConfig/AgendaFiles.swift added +44 · view
@@ -0,0 +1,44 @@
1import Foundation
2import OrgCore
3
4/// `org-agenda-files` as the `(org-agenda-files)` function reads it: each entry a folder (its
5/// `.org` files not starting with a dot, in name order, not below it), an `.org` file, or a
6/// file listing more entries one per line, as the variable's string form names one.
7/// Relative paths count from `base`, standing in for `org-directory`. Missing files are left out.
8public enum AgendaFiles {
9 public static func resolve(_ entries: [String], base: String?, fileManager: FileManager = .default) -> [String] {
10 var out: [String] = []
11 var seen: Set<String> = []
12 func expand(_ entry: String, from base: String?) -> String {
13 let path = OrgPaths.expandingTilde(entry)
14 if path.hasPrefix("/") || base == nil { return (path as NSString).standardizingPath }
15 return ((base! as NSString).appendingPathComponent(path) as NSString).standardizingPath
16 }
17 func add(_ path: String) {
18 if seen.insert(path).inserted { out.append(path) }
19 }
20 func visit(_ entry: String, listed: Bool) {
21 let path = expand(entry, from: base)
22 var isDirectory: ObjCBool = false
23 guard fileManager.fileExists(atPath: path, isDirectory: &isDirectory) else { return }
24 if isDirectory.boolValue {
25 let names = (try? fileManager.contentsOfDirectory(atPath: path)) ?? []
26 for name in names.sorted() where !name.hasPrefix(".") && name.hasSuffix(".org") {
27 let file = (path as NSString).appendingPathComponent(name)
28 var dir: ObjCBool = false
29 if fileManager.fileExists(atPath: file, isDirectory: &dir), !dir.boolValue { add(file) }
30 }
31 } else if path.hasSuffix(".org") || listed {
32 add(path)
33 } else if let text = try? String(contentsOfFile: path, encoding: .utf8) {
34 // `org-read-agenda-file-list`.
35 for line in text.components(separatedBy: .newlines) {
36 let trimmed = line.trimmingCharacters(in: .whitespaces)
37 if !trimmed.isEmpty { visit(trimmed, listed: true) }
38 }
39 }
40 }
41 for entry in entries { visit(entry, listed: false) }
42 return out
43 }
44}
Sources/OrgApp/AgendaViews.swift → Sources/OrgConfig/AgendaViews.swift renamed +7 −21 · view
@@ -1,6 +1,5 @@
1import Foundation 1import Foundation
2import OrgCore 2import OrgCore
3import OrgPresentation
4 3
5/// What the agenda window shows. 4/// What the agenda window shows.
6public enum AgendaMode: Hashable, Sendable { 5public enum AgendaMode: Hashable, Sendable {
@@ -30,20 +29,6 @@ public enum AgendaMode: Hashable, Sendable {
30 } 29 }
31} 30}
32 31
33/// What one view of a block agenda shows.
34public struct AgendaBlockResult: Equatable, Sendable {
35 public let header: String
36 public let mode: AgendaMode
37 public var days: [AgendaDay] = []
38 public var list: [AgendaItem] = []
39 public var events: [AgendaEvent] = []
40
41 public var isAgenda: Bool {
42 if case .agenda = mode { return true }
43 return false
44 }
45}
46
47/// One view of a block agenda, with its own settings. 32/// One view of a block agenda, with its own settings.
48public struct AgendaBlock: Hashable, Sendable { 33public struct AgendaBlock: Hashable, Sendable {
49 public let mode: AgendaMode 34 public let mode: AgendaMode
@@ -158,8 +143,9 @@ public enum AgendaViewLoader {
158 return settings 143 return settings
159 } 144 }
160 145
161 /// The built-in views followed by the user's, and the problems found in the file. 146 /// The built-in views followed by the user's, and the problems found in the file. Stuck
162 public static func load(userFile: URL = userFile) -> (views: [AgendaViewDefinition], problems: [String]) { 147 /// views start from the `[org-stuck-projects]` settings in `defaults`.
148 public static func load(userFile: URL = userFile, defaults: UserDefaults = .standard) -> (views: [AgendaViewDefinition], problems: [String]) {
163 let interval = Perf.begin("views.load") 149 let interval = Perf.begin("views.load")
164 defer { interval.end() } 150 defer { interval.end() }
165 guard let text = try? String(contentsOf: userFile, encoding: .utf8) else { return (builtIn, []) } 151 guard let text = try? String(contentsOf: userFile, encoding: .utf8) else { return (builtIn, []) }
@@ -195,13 +181,13 @@ public enum AgendaViewLoader {
195 for (name, table, blockTables) in parsed { 181 for (name, table, blockTables) in parsed {
196 guard let settings = settings(table, &problems) else { continue } 182 guard let settings = settings(table, &problems) else { continue }
197 if blockTables.isEmpty { 183 if blockTables.isEmpty {
198 guard let mode = mode(table, name: name, &problems) else { continue } 184 guard let mode = mode(table, name: name, defaults: defaults, &problems) else { continue }
199 views.append(AgendaViewDefinition(name: name, mode: mode, settings: settings)) 185 views.append(AgendaViewDefinition(name: name, mode: mode, settings: settings))
200 continue 186 continue
201 } 187 }
202 var blocks: [AgendaBlock] = [] 188 var blocks: [AgendaBlock] = []
203 for block in blockTables { 189 for block in blockTables {
204 guard var mode = mode(block, name: name, &problems), let own = Self.settings(block, &problems) else { continue } 190 guard var mode = mode(block, name: name, defaults: defaults, &problems), let own = Self.settings(block, &problems) else { continue }
205 // The view's span and start go to agenda blocks without their own. 191 // The view's span and start go to agenda blocks without their own.
206 if case .agenda(let span, let start) = mode { 192 if case .agenda(let span, let start) = mode {
207 mode = .agenda(span: span ?? table.values["span"]?.integer, startOffset: start ?? table.values["start"]?.integer) 193 mode = .agenda(span: span ?? table.values["span"]?.integer, startOffset: start ?? table.values["start"]?.integer)
@@ -262,7 +248,7 @@ public enum AgendaViewLoader {
262 } 248 }
263 249
264 /// The view a `[[view]]` or `[[view.block]]` table describes. 250 /// The view a `[[view]]` or `[[view.block]]` table describes.
265 static func mode(_ table: TOML.Table, name: String, _ problems: inout [String]) -> AgendaMode? { 251 static func mode(_ table: TOML.Table, name: String, defaults: UserDefaults = .standard, _ problems: inout [String]) -> AgendaMode? {
266 let match = table.values["match"]?.string 252 let match = table.values["match"]?.string
267 let type = table.values["type"]?.string ?? "agenda" 253 let type = table.values["type"]?.string ?? "agenda"
268 switch type { 254 switch type {
@@ -278,7 +264,7 @@ public enum AgendaViewLoader {
278 return type.hasSuffix("match") ? .match(match, todoOnly: type == "todo-match") : .search(match, todoOnly: type == "todo-search") 264 return type.hasSuffix("match") ? .match(match, todoOnly: type == "todo-match") : .search(match, todoOnly: type == "todo-search")
279 case "stuck": 265 case "stuck":
280 if ["match", "keywords", "tags", "regexp"].allSatisfy({ table.values[$0] == nil }) { return .stuck(nil) } 266 if ["match", "keywords", "tags", "regexp"].allSatisfy({ table.values[$0] == nil }) { return .stuck(nil) }
281 var definition = OrgPreferences.stuckProjects() 267 var definition = OrgPreferences.stuckProjects(defaults)
282 if let match { definition.match = match } 268 if let match { definition.match = match }
283 if let keywords = table.values["keywords"]?.string { definition.todo = OrgPreferences.words(keywords) } 269 if let keywords = table.values["keywords"]?.string { definition.todo = OrgPreferences.words(keywords) }
284 if let tags = table.values["tags"]?.string { definition.tags = OrgPreferences.words(tags) } 270 if let tags = table.values["tags"]?.string { definition.tags = OrgPreferences.words(tags) }
Sources/OrgConfig/CaptureTemplates.swift added +194 · view
@@ -0,0 +1,194 @@
1import Foundation
2import OrgCore
3
4/// Capture templates from `capture.toml`, and capturing into their targets:
5///
6/// ```toml
7/// [[template]]
8/// key = "t"
9/// name = "Personal todo"
10/// type = "entry" # entry, item, checkitem, plain or table-line
11/// file = "todo.org" # relative to the first folder, or ~/… or /…
12/// headline = "Inbox" # or olp = "Projects/Work"; neither for the end of the file
13/// template = "* TODO %?\n%i\n%a"
14/// prepend = false
15/// ```
16///
17/// Other targets: `datetree = true` (under `olp` if given; `tree-type` "day", "week",
18/// "month", or groups such as "year quarter month"), `regexp = "…"` with `file`,
19/// `id = "…"` without `file`, `clock = true` without `file`. Other properties, as in
20/// `org-capture-templates`: `immediate-finish`, `empty-lines`, `empty-lines-before`,
21/// `empty-lines-after`, `jump-to-captured`, `clock-in`, `clock-keep`, `clock-resume`,
22/// `table-line-pos`, `time-prompt`.
23///
24/// A `[[template]]` with only `key` and `name` is a group: the templates whose keys start
25/// with its key are listed under it.
26@MainActor
27public enum CaptureTemplates {
28 public static var userFile: URL { UserConfig.file("capture.toml") }
29
30 /// The tables `RoamTemplate` reads.
31 static let roamTables: Set<String> = ["roam-template", "roam-dailies-template", "roam-ref-template"]
32
33 /// The templates in your Doom configuration.
34 public static let defaults = [
35 CaptureTemplate(key: "t", name: "Personal todo", target: .headline(file: "todo.org", headline: "Inbox"), template: "* TODO %?\n%i\n%a"),
36 CaptureTemplate(key: "n", name: "Personal notes", target: .headline(file: "notes.org", headline: "Inbox"), template: "* %u %?\n%i\n%a"),
37 ]
38
39 public static func load(userFile: URL = userFile) -> (templates: [CaptureTemplate], groups: [CaptureGroup], problems: [String]) {
40 guard let text = try? String(contentsOf: userFile, encoding: .utf8) else { return (defaults, [], []) }
41 let tables: [TOML.Table]
42 do {
43 tables = try TOML.parse(text)
44 } catch {
45 return (defaults, [], ["capture.toml: \(error)"])
46 }
47 var templates: [CaptureTemplate] = []
48 var groups: [CaptureGroup] = []
49 var problems: [String] = []
50 for table in tables where !(table.name.isEmpty && table.values.isEmpty) && !roamTables.contains(table.name) {
51 guard table.name == "template", table.isArrayElement else {
52 problems.append("capture.toml line \(table.line): expected [[template]]")
53 continue
54 }
55 let values = table.values
56 if let key = values["key"]?.string, let name = values["name"]?.string, values.count == 2 {
57 groups.append(CaptureGroup(key: key, name: name))
58 continue
59 }
60 let fileless = values["id"]?.string != nil || values["clock"]?.bool == true || values["denote"]?.bool == true
61 guard let key = values["key"]?.string, let body = values["template"]?.string, let file = values["file"]?.string ?? (fileless ? "" : nil) else {
62 problems.append("capture.toml line \(table.line): a template needs key, file and template")
63 continue
64 }
65 guard let kind = CaptureTemplate.Kind(rawValue: table.values["type"]?.string ?? "entry") else {
66 problems.append("capture.toml line \(table.line): unknown type")
67 continue
68 }
69 let olp = values["olp"]?.string.map { $0.split(separator: "/").map(String.init) }
70 let target: CaptureTemplate.Target
71 if let id = values["id"]?.string {
72 target = .id(id)
73 } else if values["clock"]?.bool == true {
74 target = .clock
75 } else if values["datetree"]?.bool == true {
76 guard let tree = CaptureTemplate.TreeType(rawValue: values["tree-type"]?.string ?? "day") else {
77 problems.append("capture.toml line \(table.line): tree-type is day, week, month, or some of year, quarter, month, week and day")
78 continue
79 }
80 target = .datetree(file: file, path: olp ?? [], tree: tree)
81 } else if let regexp = values["regexp"]?.string {
82 target = .regexp(file: file, regexp: regexp)
83 } else if let headline = values["headline"]?.string {
84 target = .headline(file: file, headline: headline)
85 } else if let olp {
86 target = .outline(file: file, path: olp)
87 } else {
88 target = .file(file)
89 }
90 templates.append(CaptureTemplate(key: key, name: values["name"]?.string ?? key, kind: kind, target: target, template: body, options: options(values)))
91 }
92 return (templates.isEmpty ? defaults : templates, templates.isEmpty ? [] : groups, problems)
93 }
94
95 /// A table's template properties beyond the target.
96 public nonisolated static func options(_ values: [String: TOML.Value]) -> CaptureTemplate.Options {
97 func flag(_ name: String) -> Bool { values[name]?.bool ?? false }
98 func lines(_ name: String) -> Int? { values[name]?.integer }
99 return CaptureTemplate.Options(
100 prepend: flag("prepend"), immediateFinish: flag("immediate-finish"), emptyLines: lines("empty-lines"),
101 emptyLinesBefore: lines("empty-lines-before"), emptyLinesAfter: lines("empty-lines-after"),
102 jumpToCaptured: flag("jump-to-captured"), clockIn: flag("clock-in"), clockKeep: flag("clock-keep"), clockResume: flag("clock-resume"),
103 tableLinePos: values["table-line-pos"]?.string, timePrompt: flag("time-prompt"), denote: flag("denote")
104 )
105 }
106
107 /// What `org-capture` lists after the keys typed so far: the groups and templates one key
108 /// longer, in the templates' order. A template with no group for its prefix is listed
109 /// too, so that it can be reached.
110 public static func menu(_ templates: [CaptureTemplate], groups: [CaptureGroup], typed: String) -> [CaptureMenuItem] {
111 let depth = typed.count + 1
112 var items: [CaptureMenuItem] = []
113 var shown: Set<String> = []
114 for template in templates where template.key.hasPrefix(typed) {
115 if template.key.count > depth, let group = groups.first(where: { $0.key == String(template.key.prefix(depth)) }) {
116 if shown.insert(group.key).inserted { items.append(.group(group)) }
117 } else {
118 items.append(.template(template))
119 }
120 }
121 for group in groups where group.key.hasPrefix(typed) && group.key.count == depth && !shown.contains(group.key) { items.append(.group(group)) }
122 return items
123 }
124
125 /// The template's name after the names of the groups above it: `Work › Meeting`.
126 public static func label(_ template: CaptureTemplate, groups: [CaptureGroup]) -> String {
127 let names = (1..<max(1, template.key.count)).compactMap { n in groups.first { $0.key == String(template.key.prefix(n)) }?.name }
128 return (names + [template.name]).joined(separator: " › ")
129 }
130}
131
132/// A key and a description with no template: `("w" "Work")` in `org-capture-templates`.
133public struct CaptureGroup: Sendable, Equatable, Identifiable {
134 public let key: String
135 public let name: String
136 public var id: String { key }
137 public init(key: String, name: String) {
138 self.key = key
139 self.name = name
140 }
141}
142
143public enum CaptureMenuItem: Identifiable {
144 case group(CaptureGroup)
145 case template(CaptureTemplate)
146 public var key: String {
147 switch self {
148 case .group(let g): g.key
149 case .template(let t): t.key
150 }
151 }
152 public var id: String { key }
153}
154
155extension CaptureContext {
156 /// `%[file]` reads the file, a relative path from the configuration folder.
157 public mutating func readsTemplateFiles(from directory: URL = UserConfig.directory) {
158 self.directory = directory.path
159 readFile = { try? String(contentsOfFile: $0, encoding: .utf8) }
160 }
161}
162
163extension CaptureTemplates {
164 /// A template's file: absolute, `~/…`, or relative to `root`.
165 public nonisolated static func path(_ file: String, root: String?) -> String {
166 if file.hasPrefix("/") { return file }
167 if file.hasPrefix("~") { return OrgPaths.expandingTilde(file) }
168 return ((root ?? OrgPaths.home) as NSString).appendingPathComponent(file)
169 }
170}
171
172/// The edit `Capture.place` makes, as a command so the save path applies it. The selection
173/// it leaves is the captured entry's start.
174public struct CapturePlacement: OrgCommand {
175 let text: String
176 let template: CaptureTemplate
177
178 public init(text: String, template: CaptureTemplate) {
179 self.text = text
180 self.template = template
181 }
182
183 public var id: String { "internal.capture" }
184 public var title: String { "Capture" }
185 public func applies(in context: EditContext) -> Bool { true }
186 public func run(in context: EditContext) -> CommandStep {
187 switch Capture.placement(text, template: template, in: context.text, settings: context.tree.settings, now: context.now, calendar: context.calendar) {
188 case .failure(.message(let message)):
189 return .failed(message)
190 case .success(let placed):
191 return .commit(EditResult(baseRevision: context.revision, edits: TextEdit.between(context.text, placed.text), selection: [placed.start..<placed.start]))
192 }
193 }
194}
Sources/OrgApp/KeyBarLayout.swift → Sources/OrgConfig/KeyBarLayout.swift renamed · view
Sources/OrgApp/OrgPreferences.swift → Sources/OrgConfig/OrgPreferences.swift renamed +4 −25 · view
@@ -1,6 +1,5 @@
1import Foundation 1import Foundation
2import OrgCore 2import OrgCore
3import OrgPresentation
4 3
5/// The Org settings `config.toml` holds, read from user defaults with the file's fallbacks, for 4/// The Org settings `config.toml` holds, read from user defaults with the file's fallbacks, for
6/// both apps. 5/// both apps.
@@ -80,23 +79,6 @@ public enum OrgPreferences {
80 ) 79 )
81 } 80 }
82 81
83 /// `colors` with the type settings of `[theme]`: font, size, line spacing, heading step.
84 public static func theme(_ colors: ThemeSpec, _ defaults: UserDefaults = .standard) -> ThemeSpec {
85 var spec = colors
86 spec.font = string("themeFont", defaults)
87 spec.bodyFont = string("themeBodyFont", defaults)
88 spec.fontSize = integer("themeFontSize", defaults)
89 spec.lineSpacing = integer("themeLineSpacing", defaults)
90 spec.textWidth = integer("themeTextWidth", defaults)
91 spec.headingSizeStep = integer("themeHeadingStep", defaults)
92 return spec
93 }
94
95 /// `pdf-margin`, `pdf-font` and `pdf-page-numbers`.
96 @MainActor
97 public static func pdfOptions(_ defaults: UserDefaults = .standard) -> PDFExport.Options {
98 PDFExport.Options(margin: integer("pdfMargin", defaults), font: string("pdfFont", defaults), pageNumbers: bool("pdfPageNumbers", defaults))
99 }
100 82
101 /// `show-markup`: link brackets and emphasis markers shown. 83 /// `show-markup`: link brackets and emphasis markers shown.
102 public static func showMarkup(_ defaults: UserDefaults = .standard) -> Bool { bool("showMarkup", defaults) } 84 public static func showMarkup(_ defaults: UserDefaults = .standard) -> Bool { bool("showMarkup", defaults) }
@@ -242,10 +224,6 @@ public enum OrgPreferences {
242 public static func yankImageSaveMethod(_ defaults: UserDefaults = .standard) -> String { 224 public static func yankImageSaveMethod(_ defaults: UserDefaults = .standard) -> String {
243 string("yankImageSaveMethod", defaults).nonEmpty ?? "attach" 225 string("yankImageSaveMethod", defaults).nonEmpty ?? "attach"
244 } 226 }
245 /// `org-yank-dnd-method`.
246 public static func yankDndMethod(_ defaults: UserDefaults = .standard) -> ImageYank.DropMethod {
247 ImageYank.DropMethod(rawValue: string("yankDndMethod", defaults)) ?? .ask
248 }
249 /// `org-crypt-tag-matcher`, a tag. 227 /// `org-crypt-tag-matcher`, a tag.
250 public static func cryptTag(_ defaults: UserDefaults = .standard) -> String { 228 public static func cryptTag(_ defaults: UserDefaults = .standard) -> String {
251 let tag = string("cryptTagMatcher", defaults).trimmingCharacters(in: .whitespaces) 229 let tag = string("cryptTagMatcher", defaults).trimmingCharacters(in: .whitespaces)
@@ -294,16 +272,17 @@ public enum OrgPreferences {
294 UserConfig.settings.first { $0.defaultsKey == key }?.fallback 272 UserConfig.settings.first { $0.defaultsKey == key }?.fallback
295 } 273 }
296 274
297 private static func bool(_ key: String, _ defaults: UserDefaults) -> Bool { 275 /// A setting by its user-defaults key, the file's fallback when it isn't set.
276 public static func bool(_ key: String, _ defaults: UserDefaults) -> Bool {
298 defaults.object(forKey: key) as? Bool ?? fallback(key)?.bool ?? false 277 defaults.object(forKey: key) as? Bool ?? fallback(key)?.bool ?? false
299 } 278 }
300 279
301 private static func string(_ key: String, _ defaults: UserDefaults) -> String { 280 public static func string(_ key: String, _ defaults: UserDefaults) -> String {
302 defaults.string(forKey: key) ?? fallback(key)?.string ?? "" 281 defaults.string(forKey: key) ?? fallback(key)?.string ?? ""
303 } 282 }
304 283
305 /// Integers, and day offsets stored as integers with a string such as `"+0d"` as the fallback. 284 /// Integers, and day offsets stored as integers with a string such as `"+0d"` as the fallback.
306 private static func integer(_ key: String, _ defaults: UserDefaults) -> Int { 285 public static func integer(_ key: String, _ defaults: UserDefaults) -> Int {
307 if let value = defaults.object(forKey: key) as? Int { return value } 286 if let value = defaults.object(forKey: key) as? Int { return value }
308 switch fallback(key) { 287 switch fallback(key) {
309 case .integer(let value)?: return value 288 case .integer(let value)?: return value
Sources/OrgApp/Perf.swift → Sources/OrgConfig/Perf.swift renamed · view
Sources/OrgConfig/RefileSettings.swift added +135 · view
@@ -0,0 +1,135 @@
1import Foundation
2import OrgCore
3
4/// `org-refile-targets`, `org-refile-use-outline-path` and
5/// `org-refile-allow-creating-parent-nodes` (Org 9.8.7).
6public struct RefileSettings: Sendable, Equatable {
7 /// Where an `org-refile-targets` entry looks.
8 public enum Files: Sendable, Equatable {
9 /// `nil`: the file refiled from.
10 case current
11 case agendaFiles
12 case paths([String])
13 /// Every org file in the folders: orgstar's default.
14 case workspace
15 }
16
17 /// Which headings an entry offers.
18 public enum Spec: Sendable, Equatable {
19 /// `t`: every heading.
20 case all
21 case tag(String), todo(String)
22 /// An Emacs regexp.
23 case regexp(String)
24 case level(Int), maxLevel(Int)
25 }
26
27 public struct Target: Sendable, Equatable {
28 public var files: Files
29 public var spec: Spec
30
31 public init(files: Files, spec: Spec) {
32 self.files = files
33 self.spec = spec
34 }
35 }
36
37 public enum OutlinePath: String, Sendable, CaseIterable {
38 case none = "nil", full = "t", file, fullFilePath = "full-file-path", bufferName = "buffer-name", title
39 }
40
41 public enum Creating: String, Sendable, CaseIterable {
42 case no = "nil", yes = "t", confirm
43 }
44
45 public enum Failure: Error, Equatable {
46 case message(String)
47 }
48
49 public var targets: [Target]
50 public var outlinePath: OutlinePath
51 public var creating: Creating
52
53 /// Headings down to level 3 in every file, as orgstar offers with no `org-refile-targets`.
54 public static let workspaceTargets = [Target(files: .workspace, spec: .maxLevel(3))]
55
56 public init(targets: [Target] = workspaceTargets, outlinePath: OutlinePath = .file, creating: Creating = .no) {
57 self.targets = targets
58 self.outlinePath = outlinePath
59 self.creating = creating
60 }
61
62 /// An `org-refile-targets` value as Lisp writes it: `((nil :maxlevel . 3)
63 /// (org-agenda-files :tag . "project") ("~/notes/x.org" :level . 1))`. Empty text is
64 /// orgstar's default.
65 public static func parseTargets(_ text: String) -> Result<[Target], Failure> {
66 guard text.contains(where: { !$0.isWhitespace }) else { return .success(workspaceTargets) }
67 let value: Sexp
68 do {
69 guard let form = try LispReader.read(text).first?.sexp else { return .success(workspaceTargets) }
70 value = form
71 } catch {
72 return .failure(.message("can't read \(text)"))
73 }
74 func unquote(_ s: Sexp) -> Sexp {
75 if case .list(let items) = s, items.count == 2, items[0].symbol == "quote" { return items[1] }
76 return s
77 }
78 guard let entries = unquote(value).elements else { return .failure(.message("not a list of targets")) }
79 var targets: [Target] = []
80 for entry in entries {
81 // `(FILES . (KEY . VALUE))`, read as `(FILES KEY . VALUE)`, or `(FILES KEY VALUE)`.
82 let head: Sexp
83 var key: String?
84 var argument: Sexp?
85 switch entry {
86 case .dotted(let items, let last) where items.count == 2:
87 head = items[0]
88 key = items[1].symbol
89 argument = last
90 case .list(let items) where items.count == 3:
91 head = items[0]
92 key = items[1].symbol
93 argument = items[2]
94 case .dotted(let items, let last) where items.count == 1 && last.symbol == "t":
95 head = items[0]
96 key = "t"
97 default:
98 return .failure(.message("\(entry.description) isn't a target"))
99 }
100 let files: Files
101 switch head {
102 case .symbol("nil"): files = .current
103 case .symbol("org-agenda-files"): files = .agendaFiles
104 case .string(let path): files = .paths([path])
105 case .list(let items) where items.allSatisfy({ $0.string != nil }): files = .paths(items.compactMap(\.string))
106 default: return .failure(.message("files \(head.description) aren't supported"))
107 }
108 let spec: Spec
109 switch (key, argument) {
110 case ("t"?, _): spec = .all
111 case (":tag"?, .string(let s)?): spec = .tag(s)
112 case (":todo"?, .string(let s)?): spec = .todo(s)
113 case (":regexp"?, .string(let s)?): spec = .regexp(s)
114 case (":level"?, .integer(let n)?): spec = .level(n)
115 case (":maxlevel"?, .integer(let n)?): spec = .maxLevel(n)
116 default: return .failure(.message("\(entry.description) isn't a target"))
117 }
118 targets.append(Target(files: files, spec: spec))
119 }
120 return .success(targets)
121 }
122
123 /// `org-refile-get-targets`'s `descre` for `spec`, in Emacs syntax.
124 public static func regexp(_ spec: Spec) -> String {
125 func quote(_ s: String) -> String { s.map { "[*.\\?+^$".contains($0) ? "\\" + String($0) : String($0) }.joined() }
126 switch spec {
127 case .all: return "^\\*+[ \t]"
128 case .tag(let tag): return "^\\*+[ \t]+.*?:" + quote(tag) + ":"
129 case .todo(let keyword): return "^\\*+[ \t]+" + quote(keyword) + "[ \t]"
130 case .regexp(let re): return re
131 case .level(let n): return "^\\*\\{\(n)\\}[ \t]"
132 case .maxLevel(let n): return "^\\*\\{1,\(n)\\}[ \t]"
133 }
134 }
135}
Sources/OrgConfig/TangleWriter.swift added +61 · view
@@ -0,0 +1,61 @@
1import Foundation
2import OrgCore
3
4/// Writes what `Tangle.run` produced, as `org-babel-tangle` does: a file whose contents
5/// haven't changed is left alone, `:mkdirp` makes its folder, a read-only file is replaced,
6/// and the mode is set after writing. A mode that can't be set doesn't stop the others.
7public enum TangleWriter {
8 public struct Failure: Error, Equatable {
9 public let message: String
10 }
11
12 /// The paths written or already up to date, in order.
13 @discardableResult
14 public static func write(_ output: Tangle.Output, source: String) throws(Failure) -> [String] {
15 let manager = FileManager.default
16 var paths: [String] = []
17 var modeFailure: Failure?
18 for file in output.files {
19 let url = URL(fileURLWithPath: file.path)
20 let data = Data(file.contents.utf8)
21 if let existing = manager.contents(atPath: file.path), existing == data {
22 paths.append(file.path)
23 continue
24 }
25 if (file.path as NSString).standardizingPath == (source as NSString).standardizingPath {
26 throw Failure(message: "Not allowed to tangle into the same file as self")
27 }
28 let folder = url.deletingLastPathComponent()
29 if file.makeDirectories {
30 do {
31 try manager.createDirectory(at: folder, withIntermediateDirectories: true)
32 } catch {
33 throw Failure(message: "Can't make \(folder.path): \(error.localizedDescription)")
34 }
35 }
36 if manager.fileExists(atPath: file.path), !manager.isWritableFile(atPath: file.path) {
37 try? manager.removeItem(at: url)
38 }
39 do {
40 try data.write(to: url)
41 } catch {
42 throw Failure(message: "Can't write \(file.path): \(error.localizedDescription)")
43 }
44 if let mode = file.mode {
45 do {
46 try manager.setAttributes([.posixPermissions: mode], ofItemAtPath: file.path)
47 } catch {
48 modeFailure = modeFailure ?? Failure(message: "\(message(output, source: source)), but can't set the mode of \(file.path): \(error.localizedDescription)")
49 }
50 }
51 paths.append(file.path)
52 }
53 if let modeFailure { throw modeFailure }
54 return paths
55 }
56
57 /// `org-babel-tangle`'s message.
58 public static func message(_ output: Tangle.Output, source: String) -> String {
59 "Tangled \(output.blocks) code block\(output.blocks == 1 ? "" : "s") from \((source as NSString).lastPathComponent)"
60 }
61}
Sources/OrgApp/UserConfig.swift → Sources/OrgConfig/UserConfig.swift renamed +7 −46 · view
@@ -1,6 +1,5 @@
1import Foundation 1import Foundation
2import OrgCore 2import OrgCore
3import OrgPresentation
4import OrgWorkspace 3import OrgWorkspace
5 4
6/// The configuration folder (`$XDG_CONFIG_HOME/orgstar`, else `~/.config/orgstar`) and 5/// The configuration folder (`$XDG_CONFIG_HOME/orgstar`, else `~/.config/orgstar`) and
@@ -32,44 +31,6 @@ public enum UserConfig {
32 return URL(fileURLWithPath: home).appendingPathComponent(".config/orgstar") 31 return URL(fileURLWithPath: home).appendingPathComponent(".config/orgstar")
33 } 32 }
34 33
35 /// The theme `config.toml` (`text`) sets: its `[theme]` tables' colors over those of
36 /// `theme-file` (a path relative to `folder`), over the palettes `light-theme` and
37 /// `dark-theme` name; with problems in all three. Nil when `text` isn't TOML.
38 public static func theme(
39 config text: String, themeFile name: String?, lightTheme: String? = nil, darkTheme: String? = nil, in folder: URL,
40 read: (URL) -> String? = { try? String(contentsOf: $0, encoding: .utf8) }
41 ) -> (theme: ThemeSpec, problems: [String])? {
42 guard let tables = try? TOML.parse(text) else { return nil }
43 var (spec, problems) = ThemeSpec.base(light: lightTheme, dark: darkTheme)
44 if let name, !name.isEmpty {
45 if let themeText = read(folder.appendingPathComponent(name)) {
46 do {
47 let (read, more) = ThemeSpec.reading(try TOML.parse(themeText), over: spec, file: name)
48 spec = read
49 problems += more
50 } catch {
51 problems.append("\(name): \(error)")
52 }
53 } else {
54 problems.append("config.toml: theme-file \(name) can't be read")
55 }
56 }
57 let (merged, more) = ThemeSpec.reading(tables, over: spec)
58 return (merged, problems + more)
59 }
60
61 /// The file Copy to Config Folder writes.
62 public static let copiedThemeFile = "my-theme.toml"
63
64 /// Writes the two palettes into `folder` as `copiedThemeFile`; false, writing nothing, when
65 /// the file is already there.
66 public static func copyTheme(light: Palette, dark: Palette, to folder: URL) throws -> Bool {
67 let file = folder.appendingPathComponent(copiedThemeFile)
68 guard !FileManager.default.fileExists(atPath: file.path) else { return false }
69 try ThemeSpec.themeFile(light: light, dark: dark).write(to: file, atomically: true, encoding: .utf8)
70 return true
71 }
72
73 /// Where earlier versions kept the configuration files. 34 /// Where earlier versions kept the configuration files.
74 public static var legacyDirectory: URL { 35 public static var legacyDirectory: URL {
75 FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0].appendingPathComponent("Orgstar") 36 FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0].appendingPathComponent("Orgstar")
@@ -415,7 +376,7 @@ public enum UserConfig {
415 ] 376 ]
416 377
417 /// `"-3d"` as -3; nil for anything else. 378 /// `"-3d"` as -3; nil for anything else.
418 static func dayOffset(_ s: String) -> Int? { 379 public static func dayOffset(_ s: String) -> Int? {
419 guard s.hasSuffix("d"), let n = Int(s.dropLast().replacingOccurrences(of: "+", with: "")) else { return nil } 380 guard s.hasSuffix("d"), let n = Int(s.dropLast().replacingOccurrences(of: "+", with: "")) else { return nil }
420 return n 381 return n
421 } 382 }
@@ -446,7 +407,7 @@ public enum UserConfig {
446 } 407 }
447 408
448 /// Stores a file value; a value of the wrong kind is a problem. 409 /// Stores a file value; a value of the wrong kind is a problem.
449 static func store(_ value: TOML.Value, _ setting: Setting, in defaults: UserDefaults) -> String? { 410 public static func store(_ value: TOML.Value, _ setting: Setting, in defaults: UserDefaults) -> String? {
450 let key = setting.defaultsKey 411 let key = setting.defaultsKey
451 switch (setting.kind, value) { 412 switch (setting.kind, value) {
452 case (.lineNumbers, .bool(let b)): 413 case (.lineNumbers, .bool(let b)):
@@ -540,10 +501,10 @@ public enum UserConfig {
540 continue 501 continue
541 } 502 }
542 // Colors are the theme's to read; publishing projects are `Publish`'s. 503 // Colors are the theme's to read; publishing projects are `Publish`'s.
543 if ThemeSpec.isThemeTable(table.name), table.name != "theme" { continue } 504 if ThemeTables.isThemeTable(table.name), table.name != "theme" { continue }
544 if table.name == "publish", table.isArrayElement { continue } 505 if table.name == "publish", table.isArrayElement { continue }
545 for (key, value) in table.values.sorted(by: { $0.key < $1.key }) { 506 for (key, value) in table.values.sorted(by: { $0.key < $1.key }) {
546 if table.name == "theme", !ThemeSpec.typeKeys.contains(key) { continue } 507 if table.name == "theme", !ThemeTables.typeKeys.contains(key) { continue }
547 let name = path(table.name, key) 508 let name = path(table.name, key)
548 guard let setting = settings.first(where: { $0.path == name || $0.legacy == name }) else { 509 guard let setting = settings.first(where: { $0.path == name || $0.legacy == name }) else {
549 problems.append("config.toml: unknown setting \(name)") 510 problems.append("config.toml: unknown setting \(name)")
@@ -589,7 +550,7 @@ public enum UserConfig {
589 defaults.set(templates.map { $0.key + "\t" + $0.text }, forKey: denoteTemplatesKey) 550 defaults.set(templates.map { $0.key + "\t" + $0.text }, forKey: denoteTemplatesKey)
590 } 551 }
591 552
592 static func path(_ section: String, _ key: String) -> String { section.isEmpty ? key : section + "." + key } 553 public static func path(_ section: String, _ key: String) -> String { section.isEmpty ? key : section + "." + key }
593 554
594 /// Whether the file uses names from before settings took Emacs's names. 555 /// Whether the file uses names from before settings took Emacs's names.
595 public static func usesLegacyNames(_ text: String) -> Bool { 556 public static func usesLegacyNames(_ text: String) -> Bool {
@@ -650,7 +611,7 @@ public enum UserConfig {
650 } 611 }
651 612
652 /// The values a file sets, by `section.key`. 613 /// The values a file sets, by `section.key`.
653 static func values(in text: String) -> [String: TOML.Value] { 614 public static func values(in text: String) -> [String: TOML.Value] {
654 guard let tables = try? TOML.parse(text) else { return [:] } 615 guard let tables = try? TOML.parse(text) else { return [:] }
655 var result: [String: TOML.Value] = [:] 616 var result: [String: TOML.Value] = [:]
656 for table in tables { for (key, value) in table.values { result[path(table.name, key)] = value } } 617 for table in tables { for (key, value) in table.values { result[path(table.name, key)] = value } }
@@ -659,7 +620,7 @@ public enum UserConfig {
659 620
660 // MARK: - Text 621 // MARK: - Text
661 622
662 static func format(_ value: TOML.Value) -> String { 623 public static func format(_ value: TOML.Value) -> String {
663 switch value { 624 switch value {
664 case .bool(let b): b ? "true" : "false" 625 case .bool(let b): b ? "true" : "false"
665 case .integer(let i): String(i) 626 case .integer(let i): String(i)
Sources/OrgApp/UserFile.swift → Sources/OrgConfig/UserFile.swift renamed · view
Sources/OrgCore/Config/ThemeTables.swift added +10 · view
@@ -0,0 +1,10 @@
1/// The tables of config.toml the theme reads: `[theme]` and `[theme.…]`.
2public enum ThemeTables {
3 /// Keys of `[theme]` that aren't colors; config.toml's settings handle them.
4 public static let typeKeys: Set<String> = ["font", "body-font", "font-size", "line-spacing", "text-width", "heading-size-step", "theme-file", "light-theme", "dark-theme"]
5
6 /// Whether a table holds theme colors.
7 public static func isThemeTable(_ name: String) -> Bool {
8 name == "theme" || name.hasPrefix("theme.")
9 }
10}
Sources/OrgPresentation/ThemeSpec.swift +2 −2 · view
@@ -192,11 +192,11 @@ public struct ThemeSpec: Equatable, Sendable {
192 // MARK: - Reading 192 // MARK: - Reading
193 193
194 /// Keys of `[theme]` that aren't colors; config.toml's settings handle them. 194 /// Keys of `[theme]` that aren't colors; config.toml's settings handle them.
195 public static let typeKeys: Set<String> = ["font", "body-font", "font-size", "line-spacing", "text-width", "heading-size-step", "theme-file", "light-theme", "dark-theme"] 195 public static var typeKeys: Set<String> { ThemeTables.typeKeys }
196 196
197 /// Whether a table holds theme colors. 197 /// Whether a table holds theme colors.
198 public static func isThemeTable(_ name: String) -> Bool { 198 public static func isThemeTable(_ name: String) -> Bool {
199 name == "theme" || name.hasPrefix("theme.") 199 ThemeTables.isThemeTable(name)
200 } 200 }
201 201
202 /// `base` with the colors of `tables` laid over it, in order; problems for keys and 202 /// `base` with the colors of `tables` laid over it, in order; problems for keys and
Sources/OrgPrograms/CommandLineTool.swift added +53 · view
@@ -0,0 +1,53 @@
1import Foundation
2
3/// The `orgstar` command, which scripts/build-app.sh puts in the app as `Contents/Helpers/orgstar`,
4/// linked into a folder on the PATH by Settings ▸ General ▸ Install Command-Line Tool….
5public enum CommandLineTool {
6 public enum Failure: Error, Equatable {
7 /// This copy of the app has no command, as a build run from SwiftPM.
8 case missing
9 /// `path` is there and isn't a link.
10 case occupied(path: String)
11 /// The link can't be made in the folder.
12 case unwritable(folder: String, reason: String)
13 }
14
15 /// The command in the app at `app`.
16 public static func helper(in app: URL = Bundle.main.bundleURL) -> URL {
17 app.appendingPathComponent("Contents/Helpers/orgstar")
18 }
19
20 /// Where choosing a folder starts: `~/.local/bin` when it's there, else `/usr/local/bin`
21 /// when it's there, else the home folder.
22 public static func suggestedFolder(home: String = NSHomeDirectory()) -> URL {
23 let local = (home as NSString).appendingPathComponent(".local/bin")
24 for path in [local, "/usr/local/bin"] where FileManager.default.fileExists(atPath: path) { return URL(fileURLWithPath: path) }
25 return URL(fileURLWithPath: home)
26 }
27
28 /// Links `folder/orgstar` to `helper`, replacing a link already there. Returns the link.
29 @discardableResult
30 public static func install(_ helper: URL, in folder: URL) throws(Failure) -> URL {
31 let manager = FileManager.default
32 guard manager.isExecutableFile(atPath: helper.path) else { throw .missing }
33 let link = folder.appendingPathComponent("orgstar")
34 if let attributes = try? manager.attributesOfItem(atPath: link.path) {
35 guard attributes[.type] as? FileAttributeType == .typeSymbolicLink else { throw .occupied(path: link.path) }
36 }
37 let temporary = folder.appendingPathComponent(".orgstar-\(UUID().uuidString)")
38 do {
39 try manager.createSymbolicLink(at: temporary, withDestinationURL: helper)
40 // rename(2) replaces a link that's there in one step.
41 guard rename(temporary.path, link.path) == 0 else {
42 let reason = String(cString: strerror(errno))
43 try? manager.removeItem(at: temporary)
44 throw Failure.unwritable(folder: folder.path, reason: reason)
45 }
46 } catch let failure as Failure {
47 throw failure
48 } catch {
49 throw .unwritable(folder: folder.path, reason: (error as NSError).localizedFailureReason ?? error.localizedDescription)
50 }
51 return link
52 }
53}
Sources/Orgstar/OrgstarApp.swift +43 · view
@@ -1154,6 +1154,39 @@ struct SettingsView: View {
1154 } 1154 }
1155 #endif 1155 #endif
1156 1156
1157 #if !APPSTORE
1158 /// Links the `orgstar` command into a folder chosen in an open panel.
1159 private func installCommandLineTool() {
1160 let panel = NSOpenPanel()
1161 panel.canChooseFiles = false
1162 panel.canChooseDirectories = true
1163 panel.canCreateDirectories = true
1164 panel.showsHiddenFiles = true
1165 panel.directoryURL = CommandLineTool.suggestedFolder()
1166 panel.prompt = String(localized: "Install", table: "DeveloperID")
1167 panel.message = String(localized: "Choose a folder on your PATH for the orgstar command, such as ~/.local/bin or /usr/local/bin.", table: "DeveloperID")
1168 guard panel.runModal() == .OK, let folder = panel.url else { return }
1169 let helper = CommandLineTool.helper()
1170 let alert = NSAlert()
1171 alert.messageText = String(localized: "Couldn't Install orgstar", table: "DeveloperID")
1172 do {
1173 let link = try CommandLineTool.install(helper, in: folder)
1174 alert.messageText = String(localized: "Installed orgstar", table: "DeveloperID")
1175 alert.informativeText = String(localized: "\(OrgPaths.abbreviatingWithTilde(link.path)) runs the command in this app. Type orgstar --help in Terminal.", table: "DeveloperID")
1176 } catch {
1177 switch error {
1178 case .missing:
1179 alert.informativeText = String(localized: "This copy of orgstar has no command-line tool.", table: "DeveloperID")
1180 case .occupied(let path):
1181 alert.informativeText = String(localized: "\(path) is already there and isn't a link. Move it away or choose another folder.", table: "DeveloperID")
1182 case .unwritable(let path, let reason):
1183 alert.informativeText = String(localized: "orgstar can't write in \(path): \(reason). Choose a folder of your own, such as ~/.local/bin, or make the link in Terminal: sudo ln -sf '\(helper.path)' '\(path)/orgstar'", table: "DeveloperID")
1184 }
1185 }
1186 alert.runModal()
1187 }
1188 #endif
1189
1157 private var general: some View { 1190 private var general: some View {
1158 Form { 1191 Form {
1159 Section { 1192 Section {
@@ -1180,6 +1213,16 @@ struct SettingsView: View {
1180 .settingsFooter() 1213 .settingsFooter()
1181 } 1214 }
1182 #if !APPSTORE 1215 #if !APPSTORE
1216 Section {
1217 LabeledContent {
1218 Button { installCommandLineTool() } label: { Text("Install Command-Line Tool…", tableName: "DeveloperID") }
1219 } label: {
1220 Text("Command line", tableName: "DeveloperID")
1221 }
1222 } footer: {
1223 Text("Links the orgstar command into a folder on your PATH, to print the agenda, capture, clock in and out, and export from Terminal.", tableName: "DeveloperID")
1224 .settingsFooter()
1225 }
1183 if updates.canCheck { 1226 if updates.canCheck {
1184 Section { 1227 Section {
1185 Toggle(isOn: Binding(get: { updates.automatically }, set: { updates.automatically = $0 })) { Text("Check for updates automatically", tableName: "DeveloperID") } 1228 Toggle(isOn: Binding(get: { updates.automatically }, set: { updates.automatically = $0 })) { Text("Check for updates automatically", tableName: "DeveloperID") }
Sources/OrgstarCLI/AgendaCommand.swift added +222 · view
@@ -0,0 +1,222 @@
1import Foundation
2import OrgConfig
3import OrgCore
4
5/// `orgstar agenda [view]`: the agenda or a view of views.toml, as text the way Emacs's agenda
6/// buffer shows it, or as JSON.
7@MainActor
8enum AgendaCommand {
9 static let help = """
10 Usage: orgstar agenda [<view>] [--json]
11
12 Prints the agenda over the agenda files, with the span and start of Settings ▸ Agenda, or a
13 view by name: "TODO List", "Stuck Projects", or a [[view]] of views.toml.
14
15 Options:
16 --json the views, days and entries as JSON, with each entry's file and line
17 """
18
19 static func run(_ words: [String], _ workspace: Workspace) throws(Failure) {
20 let arguments = try Arguments(words, command: "agenda", flags: ["--json"])
21 try arguments.expect(0, 1, "agenda")
22 let defaults = workspace.defaults
23 let (views, problems) = AgendaViewLoader.load(userFile: workspace.configFile("views.toml"), defaults: defaults)
24 for problem in problems { workspace.host.error("orgstar: \(problem)\n") }
25 let name = arguments.positional.first ?? "Agenda"
26 guard let view = views.first(where: { $0.name == name }) ?? views.first(where: { $0.name.caseInsensitiveCompare(name) == .orderedSame }) else {
27 throw Failure(.notFound, "No agenda view named \(name). Views: " + views.map(\.name).joined(separator: ", "))
28 }
29 let blocks = compute(view, views: views, workspace)
30 if arguments.flags.contains("--json") {
31 workspace.host.output(JSONOutput.data(json(view: view.name, blocks, workspace)))
32 } else {
33 workspace.host.print(text(blocks, today: today(workspace), showAllDates: OrgPreferences.agendaShowAllDates(workspace.defaults)))
34 }
35 }
36
37 struct Block {
38 let mode: AgendaMode
39 let header: String?
40 var first = 0
41 var span = 0
42 var days: [AgendaDay] = []
43 var list: [AgendaItem] = []
44 }
45
46 static func today(_ workspace: Workspace) -> Int { Days.absolute(workspace.host.now, calendar: workspace.host.calendar) }
47
48 /// The view's blocks, computed as the agenda window computes them.
49 static func compute(_ view: AgendaViewDefinition, views: [AgendaViewDefinition], _ workspace: Workspace) -> [Block] {
50 let defaults = workspace.defaults
51 let host = workspace.host
52 let now = host.now
53 let calendar = host.calendar
54 let today = today(workspace)
55 let clock = calendar.dateComponents([.hour, .minute], from: now)
56 let base = OrgPreferences.agendaOptions(AgendaOptions.terminal, defaults)
57 let viewSettings = AgendaViewLoader.settings(views)
58 var jobs: [(mode: AgendaMode, options: AgendaOptions, header: String?)] = []
59 if case .blocks(let blocks) = view.mode {
60 for block in blocks { jobs.append((block.mode, block.settings.apply(to: base, view: block.mode.viewKey), block.settings.header)) }
61 } else {
62 jobs.append((view.mode, viewSettings[view.mode]?.apply(to: base, view: view.mode.viewKey) ?? base, view.settings.header))
63 }
64 let sources = sources(workspace, options: base)
65 return jobs.map { job in
66 var block = Block(mode: job.mode, header: job.header)
67 switch job.mode {
68 case .agenda(let span, let start):
69 var first = today + (start ?? OrgPreferences.agendaStartOffset(defaults))
70 let days = span ?? OrgPreferences.agendaSpan(defaults)
71 if days == 7 || days == 14 { first = Days.weekStart(first, on: OrgPreferences.agendaStartOnWeekday(defaults)) }
72 block.first = first
73 block.span = days
74 block.days = Agenda.list(sources, start: first, days: days, today: today, now: (clock.hour ?? 0, clock.minute ?? 0), options: job.options)
75 case .todo(let keywords):
76 block.list = Agenda.todoList(sources, keywords: keywords, options: job.options, today: today)
77 case .match(let match, let todoOnly):
78 block.list = Agenda.tagsMatch(sources, match: match, todoOnly: todoOnly, now: now, calendar: calendar, options: job.options)
79 case .search(let string, let todoOnly):
80 block.list = Agenda.textSearch(sources, string: string, todoOnly: todoOnly, options: job.options)
81 case .stuck(let definition):
82 block.list = Agenda.stuckProjects(sources, definition ?? job.options.stuckProjects, now: now, calendar: calendar, options: job.options)
83 case .blocks:
84 break
85 }
86 return block
87 }
88 }
89
90 /// The agenda files, parsed, without the files others archive to when
91 /// `agenda-exclude-archives` is on.
92 static func sources(_ workspace: Workspace, options: AgendaOptions) -> [AgendaSource] {
93 let blocking = options.dimBlockedTasks != .off && (options.enforceTodoDependencies || options.enforceTodoCheckboxDependencies)
94 var sources = workspace.agendaFiles.compactMap { path -> AgendaSource? in
95 guard let text = try? workspace.text(path) else { return nil }
96 return AgendaSource(path: path, text: text, defaults: workspace.settings(for: text, path: path), checksBlocking: blocking)
97 }
98 if OrgPreferences.agendaExcludeArchives(workspace.defaults) {
99 let location = OrgPreferences.options(workspace.defaults).archiveLocation ?? "%s_archive::"
100 let archives = Set(sources.flatMap { $0.archiveFiles(location: location) })
101 sources.removeAll { archives.contains($0.path) }
102 }
103 return sources
104 }
105
106 // MARK: - Text
107
108 /// Days without entries are left out unless `showAllDates`; today always shows.
109 static func text(_ blocks: [Block], today: Int, showAllDates: Bool) -> String {
110 var out: [String] = []
111 for (index, block) in blocks.enumerated() {
112 if index > 0 { out.append(String(repeating: "=", count: 80)) }
113 out.append(header(block))
114 if case .agenda = block.mode {
115 for day in block.days where showAllDates || day.isToday || !day.items.isEmpty {
116 out.append(day.header)
117 for item in day.items { out.append(line(item, today: today)) }
118 }
119 } else {
120 out += block.list.map { line($0, today: today) }
121 }
122 }
123 return out.joined(separator: "\n")
124 }
125
126 static func line(_ item: AgendaItem, today: Int) -> String {
127 item.habit.map { Habit.insertGraph($0.graph(today: today), into: item.line) } ?? item.line
128 }
129
130 /// The block's first line, as Emacs writes it unless the view overrides it.
131 static func header(_ block: Block) -> String {
132 if let header = block.header { return header }
133 switch block.mode {
134 case .agenda:
135 let name = switch block.span {
136 case 1: "Day"
137 case 7: "Week"
138 case 14: "Fortnight"
139 case 30, 31: "Month"
140 case 365: "Year"
141 default: "\(block.span) days"
142 }
143 var header = name + "-agenda"
144 if block.span < 350 {
145 let first = week(block.first)
146 let last = week(block.first + block.span - 1)
147 header += first == last ? String(format: " (W%02d)", first) : String(format: " (W%02d-W%02d)", first, last)
148 }
149 return header + ":"
150 case .todo(let keywords): return "Global list of TODO items of type: \(keywords ?? "ALL")"
151 case .match(let match, _): return "Headlines with TAGS match: \(match)"
152 case .search(let string, _): return "Search words: \(string)"
153 case .stuck: return "List of stuck projects:"
154 case .blocks: return ""
155 }
156 }
157
158 /// The ISO week of a day as `Days` numbers it.
159 static func week(_ day: Int) -> Int {
160 let d = Days.date(day)
161 var calendar = Calendar(identifier: .iso8601)
162 calendar.timeZone = TimeZone(identifier: "UTC")!
163 let date = calendar.date(from: DateComponents(year: d.year, month: d.month, day: d.day)) ?? Date()
164 return calendar.component(.weekOfYear, from: date)
165 }
166
167 // MARK: - JSON
168
169 static func json(view: String, _ blocks: [Block], _ workspace: Workspace) -> [String: Any] {
170 var texts: [String: String] = [:]
171 func entry(_ item: AgendaItem) -> [String: Any] {
172 var value: [String: Any] = [
173 "kind": item.kind.rawValue, "category": item.category, "title": item.text, "tags": item.tags, "done": item.isDone,
174 "text": line(item, today: today(workspace)),
175 ]
176 if !item.time.trimmingCharacters(in: .whitespaces).isEmpty { value["time"] = item.time.trimmingCharacters(in: .whitespaces) }
177 if !item.extra.trimmingCharacters(in: .whitespaces).isEmpty { value["extra"] = item.extra.trimmingCharacters(in: .whitespaces) }
178 if let todo = item.todo { value["todo"] = todo }
179 if let effort = item.effort { value["effort"] = effort }
180 if let path = item.path, let offset = item.headingOffset {
181 value["file"] = path
182 value["offset"] = offset
183 if texts[path] == nil { texts[path] = try? workspace.text(path) }
184 if let text = texts[path] { value["line"] = Workspace.line(of: offset, in: text) }
185 }
186 return value
187 }
188 let list = blocks.map { block -> [String: Any] in
189 var value: [String: Any] = ["header": header(block), "type": type(block.mode)]
190 if case .agenda = block.mode {
191 value["days"] = block.days.map { day -> [String: Any] in
192 let d = Days.date(day.day)
193 return ["date": String(format: "%04d-%02d-%02d", d.year, d.month, d.day), "today": day.isToday, "header": day.header,
194 "entries": day.items.map(entry)]
195 }
196 } else {
197 value["entries"] = block.list.map(entry)
198 }
199 return value
200 }
201 return ["view": view, "blocks": list]
202 }
203
204 static func type(_ mode: AgendaMode) -> String {
205 switch mode {
206 case .agenda: "agenda"
207 case .todo: "todo"
208 case .match(_, let todoOnly): todoOnly ? "todo-match" : "match"
209 case .search(_, let todoOnly): todoOnly ? "todo-search" : "search"
210 case .stuck: "stuck"
211 case .blocks: "blocks"
212 }
213 }
214}
215
216enum JSONOutput {
217 static func data(_ value: Any) -> Data {
218 var data = (try? JSONSerialization.data(withJSONObject: value, options: [.prettyPrinted, .sortedKeys, .withoutEscapingSlashes])) ?? Data()
219 data.append(0x0A)
220 return data
221 }
222}
Sources/OrgstarCLI/Arguments.swift added +45 · view
@@ -0,0 +1,45 @@
1/// A command's words after its name: positional arguments, flags, and options with a value,
2/// as `--name value` or `--name=value`. `--` ends the options.
3struct Arguments {
4 var positional: [String] = []
5 var flags: Set<String> = []
6 var options: [String: [String]] = [:]
7
8 /// `aliases` maps short names, such as `-o`, to long ones.
9 init(_ words: [String], command: String, flags known: Set<String>, options takes: Set<String> = [], aliases: [String: String] = [:]) throws(Failure) {
10 var rest = words[...]
11 while let word = rest.popFirst() {
12 if word == "--" {
13 positional += rest
14 break
15 }
16 guard word.hasPrefix("-"), word != "-" else {
17 positional.append(word)
18 continue
19 }
20 var name = word
21 var value: String?
22 if let equals = word.firstIndex(of: "="), word.hasPrefix("--") {
23 name = String(word[..<equals])
24 value = String(word[word.index(after: equals)...])
25 }
26 name = aliases[name] ?? name
27 if known.contains(name), value == nil {
28 flags.insert(name)
29 } else if takes.contains(name) {
30 guard let given = value ?? rest.popFirst() else { throw Failure(.usage, "\(command): \(name) needs a value") }
31 options[name, default: []].append(given)
32 } else {
33 throw Failure(.usage, "\(command): unknown option \(word)")
34 }
35 }
36 }
37
38 func value(_ name: String) -> String? { options[name]?.last }
39
40 /// Throws unless there are between `min` and `max` positional arguments.
41 func expect(_ min: Int, _ max: Int, _ command: String) throws(Failure) {
42 if positional.count < min { throw Failure(.usage, "\(command): missing argument; see orgstar \(command) --help") }
43 if positional.count > max { throw Failure(.usage, "\(command): unexpected argument \(positional[max])") }
44 }
45}
Sources/OrgstarCLI/CaptureCommand.swift added +112 · view
@@ -0,0 +1,112 @@
1import Foundation
2import OrgConfig
3import OrgCore
4
5/// `orgstar capture <key> [text]`: a template of capture.toml filled and filed at once, as
6/// Shortcuts' Capture to Orgstar does.
7@MainActor
8enum CaptureCommand {
9 static let help = """
10 Usage: orgstar capture <key> [<text>] [--set <prompt>=<value>]...
11
12 Files an entry with the capture template <key> of capture.toml, without the capture window.
13 The text is %i: the argument, or standard input when there is none.
14
15 A template's %^{Prompt} questions take their answers from --set Prompt=value, or their default
16 (%^{Prompt|default}). A question with neither stops the capture, naming what to set. %^g and
17 %^G add no tags, %^t and the other dates are today, unless set (--set Tags=work:urgent,
18 --set Date=+2d). %a, %c, %x and %f are empty.
19
20 Options:
21 --set <prompt>=<value> answer a question; may be repeated
22 """
23
24 static func run(_ words: [String], _ workspace: Workspace) throws(Failure) {
25 let arguments = try Arguments(words, command: "capture", flags: [], options: ["--set"])
26 try arguments.expect(1, 2, "capture")
27 let key = arguments.positional[0]
28 var answers: [String: String] = [:]
29 for pair in arguments.options["--set"] ?? [] {
30 guard let equals = pair.firstIndex(of: "=") else { throw Failure(.usage, "capture: --set takes prompt=value, not \(pair)") }
31 answers[String(pair[..<equals])] = String(pair[pair.index(after: equals)...])
32 }
33 let (templates, _, problems) = CaptureTemplates.load(userFile: workspace.configFile("capture.toml"))
34 for problem in problems { workspace.host.error("orgstar: \(problem)\n") }
35 guard let template = templates.first(where: { $0.key == key }) else {
36 throw Failure(.notFound, "No capture template \"\(key)\". Templates: " + templates.map { "\($0.key) (\($0.name))" }.joined(separator: ", "))
37 }
38 if template.options.denote { throw Failure(.refused, "Template \"\(key)\" makes a Denote note; capture with it in orgstar.") }
39 var initial = arguments.positional.count > 1 ? arguments.positional[1] : workspace.host.input() ?? ""
40 if initial.hasSuffix("\n") { initial.removeLast() }
41
42 let running = ClockCommand.running(workspace)
43 var context = CaptureContext(
44 now: workspace.host.now, calendar: workspace.host.calendar, initial: initial, userName: NSFullUserName(),
45 clockHeading: running?.title ?? "", clockLink: running.map { "[[file:\($0.path)::*\($0.title)][\($0.title)]]" } ?? "",
46 tagsColumn: workspace.options.tagsColumn
47 )
48 context.readsTemplateFiles(from: workspace.configDirectory)
49 let questions = Capture.questions(template.template, context: context)
50 var replies: [String] = []
51 var missing: [String] = []
52 for question in questions {
53 if let answer = answers[question.prompt] {
54 replies.append(answer)
55 continue
56 }
57 switch question.kind {
58 case .text, .property:
59 if question.defaultValue.isEmpty { missing.append(question.prompt) }
60 replies.append(question.defaultValue)
61 case .tags, .date, .clipboard:
62 replies.append("")
63 }
64 }
65 if !missing.isEmpty {
66 let names = missing.map { "\"\($0)\"" }.joined(separator: ", ")
67 throw Failure(.refused, "Template \"\(key)\" asks \(names). Answer with --set, as: --set '\(missing[0])=…'")
68 }
69 guard case .success(let filled) = Capture.fill(template.template, context: context, answers: replies) else {
70 throw Failure(.failure, "Can't fill template \"\(key)\"")
71 }
72
73 var chosen = template
74 let path: String
75 switch template.target {
76 case .id(let id):
77 path = try workspace.target("id:" + id).path
78 case .clock:
79 guard let running else { throw Failure(.notFound, "Template \"\(key)\" files under the running clock, and no clock runs.") }
80 let text = try workspace.text(running.path)
81 let line = (text as NSString).range(of: "CLOCK: [\(running.start)]").location
82 guard let heading = workspace.headings(text, path: running.path).last(where: { $0.headingRange.lowerBound <= line }) else {
83 throw Failure(.notFound, "The running clock's heading wasn't found.")
84 }
85 chosen = template.retargeted(.heading(file: running.path, offset: heading.headingRange.lowerBound))
86 path = running.path
87 default:
88 path = CaptureTemplates.path(template.target.file, root: workspace.roots.first)
89 }
90 if !FileManager.default.fileExists(atPath: path) {
91 do {
92 try FileManager.default.createDirectory(at: URL(fileURLWithPath: path).deletingLastPathComponent(), withIntermediateDirectories: true)
93 try Data().write(to: URL(fileURLWithPath: path))
94 } catch {
95 throw Failure(.failure, "Can't create \(path): \(error.localizedDescription)")
96 }
97 }
98 let (result, text) = try workspace.perform(CapturePlacement(text: filled.text, template: chosen), path: path, at: 0)
99 let offset = result.selection?.first?.lowerBound ?? 0
100 workspace.host.print("Captured to \(path):\(Workspace.line(of: offset, in: text))")
101 // A template's clock-in, kept running: the capture is filed at once, so without
102 // clock-keep the clock would stop as it starts.
103 let headings = workspace.headings(text, path: path)
104 if template.options.clockIn, template.options.clockKeep, let index = headings.lastIndex(where: { $0.headingRange.lowerBound <= offset }) {
105 let entry = ClockTask(path: path, title: headings[index].title, ordinal: index, id: headings[index].id)
106 try ClockCommand.clockIn(workspace) { () throws(Failure) in
107 guard let start = entry.locate(in: try workspace.text(path)) else { throw Failure(.notFound, "The captured entry wasn't found.") }
108 return Workspace.Target(path: path, offset: start, title: entry.title)
109 }
110 }
111 }
112}
Sources/OrgstarCLI/ClockCommand.swift added +148 · view
@@ -0,0 +1,148 @@
1import Foundation
2import OrgCore
3
4/// `orgstar clock in|out|status`. The running clock is the open `CLOCK:` line in the files, as
5/// in Emacs: the tool changes only the org file, and the app, which watches its folders, takes
6/// a clock started or stopped here as the running one. The app's own record (`clock.json` in
7/// the data folder) is read, never written, so the two never write the same file.
8@MainActor
9enum ClockCommand {
10 static let help = """
11 Usage: orgstar clock in <file>::<heading>
12 orgstar clock in <file>::id:<id> | id:<id>
13 orgstar clock out
14 orgstar clock status [--json]
15
16 Starts and stops the clock as Org does: clock in writes a CLOCK line under the heading,
17 stopping the running clock first; clock out closes the running clock's line. The heading is
18 its title (with or without a leading *), #custom-id or id:ID.
19
20 The running clock is the one orgstar shows, else the most recently started open CLOCK line in
21 the agenda files. orgstar picks up a clock started or stopped here when it sees the file change.
22
23 Options:
24 --json clock status as JSON
25 """
26
27 struct Running {
28 let path: String
29 let start: String
30 let startedAt: Date
31 let title: String
32 }
33
34 static func run(_ words: [String], _ workspace: Workspace) throws(Failure) {
35 guard let verb = words.first else { throw Failure(.usage, "clock: in, out or status; see orgstar clock --help") }
36 let command = "clock " + verb
37 switch verb {
38 case "in":
39 let arguments = try Arguments(Array(words.dropFirst()), command: command, flags: [])
40 try arguments.expect(1, 1, command)
41 try clockIn(arguments.positional[0], workspace)
42 case "out":
43 try Arguments(Array(words.dropFirst()), command: command, flags: []).expect(0, 0, command)
44 try clockOut(workspace)
45 case "status":
46 let arguments = try Arguments(Array(words.dropFirst()), command: command, flags: ["--json"])
47 try arguments.expect(0, 0, command)
48 try status(json: arguments.flags.contains("--json"), workspace)
49 default:
50 throw Failure(.usage, "clock: unknown subcommand \(verb); see orgstar clock --help")
51 }
52 }
53
54 static func clockIn(_ spec: String, _ workspace: Workspace) throws(Failure) {
55 try clockIn(workspace) { () throws(Failure) in try workspace.target(spec) }
56 }
57
58 /// Clocks in at the heading `resolve` finds, asked again after the running clock stops.
59 static func clockIn(_ workspace: Workspace, target resolve: () throws(Failure) -> Workspace.Target) throws(Failure) {
60 var target = try resolve()
61 guard target.offset != nil else { throw Failure(.usage, "clock in: name a heading, as file.org::Heading") }
62 if let running = running(workspace) {
63 if running.path == target.path, try heading(of: running, workspace)?.headingRange.lowerBound == target.offset {
64 workspace.host.print("Clock continues in \"\(running.title)\"")
65 return
66 }
67 workspace.host.print(try stop(running, workspace))
68 // Clocking out may have moved the heading.
69 target = try resolve()
70 }
71 guard let offset = target.offset else { return }
72 let (_, text) = try workspace.perform(ClockIn(), path: target.path, at: offset)
73 guard let start = ClockIn.runningStart(in: text, near: offset) else { throw Failure(.failure, "The clock line wasn't found after clocking in.") }
74 workspace.host.print("Clock starts at [\(start)] in \"\(target.title ?? "")\"")
75 }
76
77 static func clockOut(_ workspace: Workspace) throws(Failure) {
78 guard let running = running(workspace) else { throw Failure(.notFound, "No active clock") }
79 workspace.host.print(try stop(running, workspace))
80 }
81
82 private static func stop(_ running: Running, _ workspace: Workspace) throws(Failure) -> String {
83 let (_, text) = try workspace.perform(ClockOut(start: running.start), path: running.path, at: 0)
84 let minutes = max(0, Int(workspace.host.now.timeIntervalSince(running.startedAt) / 60))
85 let removed = !text.contains("CLOCK: [\(running.start)]")
86 return String(format: "Clock stopped after %d:%02d", minutes / 60, minutes % 60) + (removed ? " => LINE REMOVED" : "") + " in \"\(running.title)\""
87 }
88
89 static func status(json: Bool, _ workspace: Workspace) throws(Failure) {
90 let running = running(workspace)
91 if json {
92 let value: [String: Any] = running.map { running in
93 ["running": [
94 "file": running.path, "heading": running.title, "start": running.start,
95 "minutes": max(0, Int(workspace.host.now.timeIntervalSince(running.startedAt) / 60)),
96 ] as [String: Any]]
97 } ?? ["running": NSNull()]
98 workspace.host.output(JSONOutput.data(value))
99 } else if let running {
100 let minutes = max(0, Int(workspace.host.now.timeIntervalSince(running.startedAt) / 60))
101 workspace.host.print(String(format: "%d:%02d ", minutes / 60, minutes % 60) + "\(running.title) (\(running.path)) since [\(running.start)]")
102 } else {
103 workspace.host.print("No active clock")
104 }
105 if running == nil { throw Failure(.notFound, "") }
106 }
107
108 /// The clock the app shows, while its line is still open; else the most recently started
109 /// open clock in the agenda files.
110 static func running(_ workspace: Workspace) -> Running? {
111 let saved = savedRunning(workspace)
112 var paths = workspace.agendaFiles
113 if let saved, !paths.contains(saved.path) { paths.append(saved.path) }
114 var newest: Running?
115 for path in paths {
116 guard let text = try? workspace.text(path), text.contains("CLOCK: [") else { continue }
117 for clock in ClockResolution.openClocks(in: text) {
118 guard let startedAt = ClockResolution.date(of: clock.start, calendar: workspace.host.calendar) else { continue }
119 let heading = workspace.headings(text, path: path).last { $0.headingRange.lowerBound <= clock.offset }
120 let found = Running(path: path, start: clock.start, startedAt: startedAt, title: heading?.title ?? "")
121 if saved?.path == path, saved?.start == clock.start { return found }
122 if newest.map({ startedAt > $0.startedAt }) ?? true { newest = found }
123 }
124 }
125 return newest
126 }
127
128 private static func heading(of running: Running, _ workspace: Workspace) throws(Failure) -> HeadingInfo? {
129 let text = try workspace.text(running.path)
130 let offset = (text as NSString).range(of: "CLOCK: [\(running.start)]").location
131 guard offset != NSNotFound else { return nil }
132 return workspace.headings(text, path: running.path).last { $0.headingRange.lowerBound <= offset }
133 }
134
135 /// The running clock in the app's `clock.json`.
136 private static func savedRunning(_ workspace: Workspace) -> (path: String, start: String)? {
137 struct Clock: Decodable {
138 let path: String
139 let start: String
140 }
141 struct Saved: Decodable {
142 let running: Clock?
143 }
144 guard let data = try? Data(contentsOf: workspace.dataDirectory.appendingPathComponent("clock.json")) else { return nil }
145 let clock = (try? JSONDecoder().decode(Saved.self, from: data))?.running ?? (try? JSONDecoder().decode(Clock.self, from: data))
146 return clock.map { ($0.path, $0.start) }
147 }
148}
Sources/OrgstarCLI/ExportCommand.swift added +151 · view
@@ -0,0 +1,151 @@
1import Foundation
2import OrgConfig
3import OrgCore
4
5/// `orgstar export` and `orgstar tangle`.
6@MainActor
7enum ExportCommand {
8 static let help = """
9 Usage: orgstar export <file> --to <format> [-o <path>]
10
11 Exports the whole file with the settings of config.toml and the file's own, as File ▸ Export
12 does. Formats: html, md, latex, txt, odt, reveal, and pdf, which runs the LaTeX export
13 through latexmk or pdflatex, as Emacs does (the app's PDF export doesn't need TeX).
14
15 The output goes beside the file, named by #+EXPORT_FILE_NAME or the file's name, unless
16 -o names a path; -o - writes it to standard output.
17
18 Options:
19 --to <format> html, md, pdf, latex, odt, txt or reveal
20 -o, --output <path> where to write the export
21 """
22
23 static let tangleHelp = """
24 Usage: orgstar tangle <file>
25
26 Writes the file's code blocks with :tangle to their files, as org-babel-tangle does: a file
27 whose contents haven't changed is left alone, :mkdirp makes its folder, :tangle-mode sets
28 its mode.
29 """
30
31 static let extensions = ["html": "html", "md": "md", "pdf": "pdf", "latex": "tex", "odt": "odt", "txt": "txt", "reveal": "html"]
32
33 static func run(_ words: [String], _ workspace: Workspace) throws(Failure) {
34 let arguments = try Arguments(words, command: "export", flags: [], options: ["--to", "--output"], aliases: ["-o": "--output"])
35 try arguments.expect(1, 1, "export")
36 guard let format = arguments.value("--to") else { throw Failure(.usage, "export: --to is html, md, pdf, latex, odt, txt or reveal") }
37 guard let ext = extensions[format] else { throw Failure(.usage, "export: unknown format \(format); use html, md, pdf, latex, odt, txt or reveal") }
38 let host = workspace.host
39 let path = host.absolute(arguments.positional[0])
40 let text = try workspace.text(path)
41 let url = URL(fileURLWithPath: path)
42 let name = url.lastPathComponent
43 let settings = workspace.settings(for: text, path: path)
44 let language = OrgPreferences.exportLanguage(workspace.defaults)
45 let base = url.deletingPathExtension().lastPathComponent
46 let data: Data
47 do {
48 switch format {
49 case "html":
50 data = Data(HTMLExport.page(text, fallbackTitle: base, settings: settings, path: path, language: language).utf8)
51 case "md":
52 data = Data(MarkdownExport.document(text, settings: settings, path: path, bodyOnly: false).utf8)
53 case "latex":
54 data = Data(try LaTeXExport.document(text, settings: settings, path: path, bodyOnly: false, author: NSFullUserName(), language: language, file: true).utf8)
55 case "txt":
56 data = Data(try ASCIIExport.document(text, settings: settings, path: path, bodyOnly: false, author: NSFullUserName(), language: language, file: true).utf8)
57 case "odt":
58 data = try ODTExport.document(text, settings: settings, path: path, author: NSFullUserName(), language: language)
59 case "reveal":
60 let library = bundledScripts(host).map { $0.url(forResource: "Reveal", withExtension: nil) } ?? nil
61 let mathJax = bundledScripts(host).map { $0.url(forResource: "tex-svg-full", withExtension: "js", subdirectory: "MathJax") } ?? nil
62 data = Data(RevealExport.document(text, fallbackTitle: base, settings: settings, path: path, language: language, library: library, mathJax: mathJax).utf8)
63 default:
64 let latex = try LaTeXExport.document(text, settings: settings, path: path, bodyOnly: false, author: NSFullUserName(), language: language, file: true)
65 data = try pdf(latex: latex, name: base, directory: url.deletingLastPathComponent(), host)
66 }
67 } catch let failure as Failure {
68 throw failure
69 } catch let error as LaTeXExport.Unsupported {
70 throw Failure(.failure, "Can't export \(name) to \(format == "txt" ? "plain text" : "LaTeX"): \(error.reason)")
71 } catch {
72 throw Failure(.failure, "Can't export \(name): \(error.localizedDescription)")
73 }
74 if arguments.value("--output") == "-" {
75 host.output(data)
76 return
77 }
78 let target = arguments.value("--output").map { URL(fileURLWithPath: host.absolute($0)) }
79 ?? ExportScope.output(for: url, name: ExportScope.fileName(text, settings: settings), extension: ext)
80 do {
81 try FileManager.default.createDirectory(at: target.deletingLastPathComponent(), withIntermediateDirectories: true)
82 try data.write(to: target, options: .atomic)
83 } catch {
84 throw Failure(.failure, "Can't write \(target.path): \(error.localizedDescription)")
85 }
86 host.print("Exported to \(target.path)")
87 }
88
89 /// The app's bundle of scripts (reveal.js, MathJax): beside this executable in a build
90 /// folder, or in the app's resources.
91 static func bundledScripts(_ host: Host) -> Bundle? {
92 let folder = host.executable.deletingLastPathComponent()
93 let candidates = [folder, folder.deletingLastPathComponent().appendingPathComponent("Resources")]
94 return candidates.lazy.compactMap { Bundle(url: $0.appendingPathComponent("Orgstar_OrgMathJax.bundle")) }.first
95 }
96
97 /// `org-latex-export-to-pdf`: `latex` compiled in a temporary folder, run from `directory`
98 /// so that relative image paths resolve, by latexmk or else pdflatex three times.
99 static func pdf(latex: String, name: String, directory: URL, _ host: Host) throws -> Data {
100 let path = (host.environment["PATH"] ?? "/usr/bin:/bin") + ":/Library/TeX/texbin"
101 func find(_ program: String) -> String? {
102 path.split(separator: ":").map { "\($0)/\(program)" }.first { FileManager.default.isExecutableFile(atPath: $0) }
103 }
104 let work = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-pdf-\(UUID().uuidString)")
105 try FileManager.default.createDirectory(at: work, withIntermediateDirectories: true)
106 defer { try? FileManager.default.removeItem(at: work) }
107 let tex = work.appendingPathComponent(name + ".tex")
108 try latex.write(to: tex, atomically: true, encoding: .utf8)
109 let runs: [(String, [String])]
110 if let latexmk = find("latexmk") {
111 runs = [(latexmk, ["-f", "-pdf", "-interaction=nonstopmode", "-output-directory=\(work.path)", tex.path])]
112 } else if let pdflatex = find("pdflatex") {
113 runs = Array(repeating: (pdflatex, ["-interaction", "nonstopmode", "-output-directory", work.path, tex.path]), count: 3)
114 } else {
115 throw Failure(.failure, "PDF export from the command line needs TeX (latexmk or pdflatex), such as MacTeX. Export to PDF in orgstar, which doesn't.")
116 }
117 for (program, arguments) in runs {
118 let process = Process()
119 process.executableURL = URL(fileURLWithPath: program)
120 process.arguments = arguments
121 process.currentDirectoryURL = directory
122 process.standardOutput = FileHandle.nullDevice
123 process.standardError = FileHandle.nullDevice
124 try process.run()
125 process.waitUntilExit()
126 }
127 guard let data = FileManager.default.contents(atPath: work.appendingPathComponent(name + ".pdf").path) else {
128 throw Failure(.failure, "TeX made no PDF from \(name).tex; export to LaTeX and run it to see why.")
129 }
130 return data
131 }
132
133 static func tangle(_ words: [String], _ workspace: Workspace) throws(Failure) {
134 let arguments = try Arguments(words, command: "tangle", flags: [])
135 try arguments.expect(1, 1, "tangle")
136 let path = workspace.host.absolute(arguments.positional[0])
137 let text = try workspace.text(path)
138 let tree = OrgParser.parse(text, defaults: workspace.settings(for: text, path: path))
139 switch Tangle.run(text: text, path: path, scope: .all, tree: tree) {
140 case .failure(.message(let message)):
141 throw Failure(.failure, message)
142 case .success(let output):
143 do {
144 try TangleWriter.write(output, source: path)
145 } catch {
146 throw Failure(.failure, error.message)
147 }
148 workspace.host.print(TangleWriter.message(output, source: path))
149 }
150 }
151}
Sources/OrgstarCLI/Host.swift added +89 · view
@@ -0,0 +1,89 @@
1import Foundation
2
3/// What the tool takes from outside the files: the environment, the time, the standard streams
4/// and `open`. Tests give their own.
5struct Host {
6 var environment: [String: String]
7 var now: Date
8 var calendar: Calendar
9 var currentDirectory: String
10 /// Standard input's text; nil when it is a terminal.
11 var input: () -> String?
12 var output: (Data) -> Void
13 var error: (String) -> Void
14 /// Runs `/usr/bin/open` with these arguments and returns its exit status.
15 var open: ([String]) -> Int32
16 /// The running executable, through any links to it.
17 var executable: URL
18
19 static func process() -> Host {
20 Host(
21 environment: ProcessInfo.processInfo.environment,
22 now: Date(),
23 calendar: .current,
24 currentDirectory: FileManager.default.currentDirectoryPath,
25 input: {
26 guard isatty(STDIN_FILENO) == 0 else { return nil }
27 return String(decoding: FileHandle.standardInput.readDataToEndOfFile(), as: UTF8.self)
28 },
29 output: { FileHandle.standardOutput.write($0) },
30 error: { FileHandle.standardError.write(Data($0.utf8)) },
31 open: { arguments in
32 let process = Process()
33 process.executableURL = URL(fileURLWithPath: "/usr/bin/open")
34 process.arguments = arguments
35 do {
36 try process.run()
37 process.waitUntilExit()
38 return process.terminationStatus
39 } catch {
40 return 1
41 }
42 },
43 executable: URL(fileURLWithPath: CommandLine.arguments[0]).resolvingSymlinksInPath()
44 )
45 }
46
47 func print(_ text: String) {
48 output(Data((text.hasSuffix("\n") ? text : text + "\n").utf8))
49 }
50
51 /// The app this executable is inside, as `Contents/Helpers/orgstar`; nil for a build run
52 /// from its build folder.
53 var app: URL? {
54 let contents = executable.deletingLastPathComponent().deletingLastPathComponent()
55 let app = contents.deletingLastPathComponent()
56 guard executable.deletingLastPathComponent().lastPathComponent == "Helpers", contents.lastPathComponent == "Contents",
57 app.pathExtension == "app" else { return nil }
58 return app
59 }
60
61 /// `path` from the command line: `~` expanded, and relative to the current folder.
62 func absolute(_ path: String) -> String {
63 let expanded = (path as NSString).expandingTildeInPath
64 if expanded.hasPrefix("/") { return (expanded as NSString).standardizingPath }
65 return ((currentDirectory as NSString).appendingPathComponent(expanded) as NSString).standardizingPath
66 }
67}
68
69enum ExitCode: Int32 {
70 case success = 0
71 /// A file couldn't be read, written or exported.
72 case failure = 1
73 /// An unknown command or option, or a missing argument.
74 case usage = 2
75 /// No such file, heading, view or template, or no running clock.
76 case notFound = 3
77 /// The command won't do it: questions without answers, a file it can't change.
78 case refused = 4
79}
80
81struct Failure: Error {
82 let code: ExitCode
83 let message: String
84
85 init(_ code: ExitCode, _ message: String) {
86 self.code = code
87 self.message = message
88 }
89}
Sources/OrgstarCLI/Tool.swift added +120 · view
@@ -0,0 +1,120 @@
1import Foundation
2
3/// The `orgstar` command: reads the command line, runs a command, and returns the exit status.
4@MainActor
5enum Tool {
6 static let help = """
7 Usage: orgstar <command> [<arguments>]
8
9 Works on your org files directly, with orgstar's configuration folder and folders, whether or
10 not the app is running.
11
12 Commands:
13 agenda [<view>] print the agenda or a view of views.toml
14 capture <key> [<text>] file an entry with a capture template
15 clock in <file>::<heading> start the clock on a heading
16 clock out stop the running clock
17 clock status show the running clock
18 export <file> --to <format> export to html, md, pdf, latex, odt, txt or reveal
19 tangle <file> write the file's code blocks to their files
20 open <file>[::<heading>] open a file in orgstar, at a heading
21
22 Options:
23 -h, --help this help; orgstar <command> --help for a command's
24 --version the version
25
26 Exit status:
27 0 done
28 1 failed: a file couldn't be read, written or exported, or changed meanwhile
29 2 usage: an unknown command or option, or a missing argument
30 3 not found: no such file, heading, view or template; no running clock
31 4 refused: a capture question without an answer, or a file that can't be changed here
32 (encrypted, not UTF-8, or a command that needs the app)
33
34 Environment:
35 ORGSTAR_CONFIG_DIR the configuration folder, else $XDG_CONFIG_HOME/orgstar or ~/.config/orgstar
36 ORGSTAR_DATA_DIR the data folder (the app's folder list, running clock and recovery
37 versions), else ~/Library/Application Support/Orgstar
38 ORGSTAR_ROOT a folder to read besides those added in the app
39 """
40
41 static let openHelp = """
42 Usage: orgstar open <file>[::<heading>]
43 orgstar open <file>::id:<id> | id:<id>
44
45 Opens the file in orgstar, at the heading when one is named: its title (with or without a
46 leading *), #custom-id or id:ID.
47 """
48
49 static func run(_ arguments: [String], host: Host) -> Int32 {
50 guard let command = arguments.first else {
51 host.error(help + "\n")
52 return ExitCode.usage.rawValue
53 }
54 let rest = Array(arguments.dropFirst())
55 let helps = ["agenda": AgendaCommand.help, "capture": CaptureCommand.help, "clock": ClockCommand.help, "export": ExportCommand.help,
56 "tangle": ExportCommand.tangleHelp, "open": openHelp]
57 switch command {
58 case "-h", "--help", "help":
59 if let topic = rest.first {
60 guard let text = helps[topic] else { return fail(Failure(.usage, "help: no command \(topic)"), host) }
61 host.print(text)
62 } else {
63 host.print(help)
64 }
65 return ExitCode.success.rawValue
66 case "--version":
67 host.print("orgstar \(version(host))")
68 return ExitCode.success.rawValue
69 default:
70 break
71 }
72 guard let text = helps[command] else { return fail(Failure(.usage, "unknown command \(command); see orgstar --help"), host) }
73 if rest.contains("--help") || rest.contains("-h") {
74 host.print(text)
75 return ExitCode.success.rawValue
76 }
77 let workspace = Workspace(host: host)
78 do {
79 switch command {
80 case "agenda": try AgendaCommand.run(rest, workspace)
81 case "capture": try CaptureCommand.run(rest, workspace)
82 case "clock": try ClockCommand.run(rest, workspace)
83 case "export": try ExportCommand.run(rest, workspace)
84 case "tangle": try ExportCommand.tangle(rest, workspace)
85 default: try open(rest, workspace)
86 }
87 } catch {
88 return fail(error, host)
89 }
90 return ExitCode.success.rawValue
91 }
92
93 static func fail(_ failure: Failure, _ host: Host) -> Int32 {
94 if !failure.message.isEmpty { host.error("orgstar: \(failure.message)\n") }
95 return failure.code.rawValue
96 }
97
98 /// The app's version, from the Info.plist of the app around this executable.
99 static func version(_ host: Host) -> String {
100 guard let app = host.app, let info = NSDictionary(contentsOf: app.appendingPathComponent("Contents/Info.plist")),
101 let version = info["CFBundleShortVersionString"] as? String else { return "(development build)" }
102 let build = info["CFBundleVersion"] as? String
103 return build.map { $0 == version ? version : "\(version) (\($0))" } ?? version
104 }
105
106 /// `open`: the app's own link to the entry, `orgstar://entry`, opened by the app this
107 /// executable is in, else by whichever app handles the link.
108 static func open(_ words: [String], _ workspace: Workspace) throws(Failure) {
109 let arguments = try Arguments(words, command: "open", flags: [])
110 try arguments.expect(1, 1, "open")
111 let target = try workspace.target(arguments.positional[0])
112 var link = URLComponents()
113 link.scheme = "orgstar"
114 link.host = "entry"
115 link.queryItems = [URLQueryItem(name: "path", value: target.path), URLQueryItem(name: "offset", value: String(target.offset ?? 0))]
116 guard let url = link.url?.absoluteString else { throw Failure(.failure, "Can't make a link to \(target.path)") }
117 let status = workspace.host.open((workspace.host.app.map { ["-a", $0.path] } ?? []) + [url])
118 guard status == 0 else { throw Failure(.failure, "open couldn't open \(url)") }
119 }
120}
Sources/OrgstarCLI/Workspace.swift added +247 · view
@@ -0,0 +1,247 @@
1import Foundation
2import OrgConfig
3import OrgCore
4import OrgDocument
5import OrgIndex
6import OrgWorkspace
7
8/// Settings held in memory: config.toml is applied to them as the app applies it to its user
9/// defaults, and no defaults domain is written.
10final class MemoryDefaults: UserDefaults, @unchecked Sendable {
11 private var values: [String: Any] = [:]
12
13 convenience init() {
14 self.init(suiteName: nil)!
15 }
16
17 override func object(forKey defaultName: String) -> Any? { values[defaultName] }
18 override func set(_ value: Any?, forKey defaultName: String) { values[defaultName] = value }
19 override func removeObject(forKey defaultName: String) { values[defaultName] = nil }
20}
21
22/// The app's configuration and folders as the tool finds them: the configuration folder, the
23/// data folder (the folder list, the running clock, recovery versions), the settings of
24/// config.toml, and the files of the folders.
25@MainActor
26final class Workspace {
27 let host: Host
28 let configDirectory: URL
29 let dataDirectory: URL
30 let defaults = MemoryDefaults()
31 let settings: OrgSettings
32 let options: EditingOptions
33 /// The folders, by path, sorted as the app sorts them.
34 let roots: [String]
35 private var scanned: [(path: String, relative: String, kind: FileKind)]?
36
37 init(host: Host) {
38 self.host = host
39 let environment = host.environment
40 configDirectory = UserConfig.defaultDirectory(environment: environment, home: NSHomeDirectory(), sandboxed: false)
41 dataDirectory = environment["ORGSTAR_DATA_DIR"].map { URL(fileURLWithPath: $0) }
42 ?? FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0].appendingPathComponent("Orgstar")
43 var roots: Set<String> = []
44 if let data = try? Data(contentsOf: dataDirectory.appendingPathComponent("roots.json")),
45 let saved = try? JSONDecoder().decode([WorkspaceRoot].self, from: data) {
46 for root in saved {
47 if let url = try? root.resolve(sandboxed: false).url { roots.insert(url.standardizedFileURL.path) }
48 }
49 }
50 if let root = environment["ORGSTAR_ROOT"] { roots.insert(host.absolute(root)) }
51 self.roots = roots.sorted()
52 if let text = try? String(contentsOf: Self.configFile("config.toml", in: configDirectory, environment: environment), encoding: .utf8) {
53 for problem in UserConfig.apply(text, to: defaults) { host.error("orgstar: \(problem)\n") }
54 }
55 settings = OrgPreferences.orgSettings(defaults)
56 options = OrgPreferences.options(defaults)
57 }
58
59 /// A file of the configuration folder; without a folder from the environment, one that
60 /// exists only where earlier versions kept it is read from there, as the app does.
61 func configFile(_ name: String) -> URL {
62 Self.configFile(name, in: configDirectory, environment: host.environment)
63 }
64
65 private static func configFile(_ name: String, in directory: URL, environment: [String: String]) -> URL {
66 let url = directory.appendingPathComponent(name)
67 guard environment["ORGSTAR_CONFIG_DIR"] == nil, environment["ORGSTAR_DATA_DIR"] == nil else { return url }
68 let legacy = UserConfig.legacyDirectory.appendingPathComponent(name)
69 let manager = FileManager.default
70 if !manager.fileExists(atPath: url.path), manager.fileExists(atPath: legacy.path) { return legacy }
71 return url
72 }
73
74 // MARK: - Files
75
76 /// The folders' files, as the app lists them with Settings ▸ General's hidden-file and
77 /// ignored-folder settings.
78 var files: [(path: String, relative: String, kind: FileKind)] {
79 if let scanned { return scanned }
80 let rules = ScanRules(
81 hiddenFiles: OrgPreferences.bool("showHiddenFiles", defaults),
82 ignoredFolders: Set(OrgPreferences.string("ignoredFolders", defaults).split(separator: " ").map(String.init))
83 )
84 var found: [(path: String, relative: String, kind: FileKind)] = []
85 for root in roots {
86 guard let discovery = try? WorkspaceScanner.scan(URL(fileURLWithPath: root), rules: rules) else { continue }
87 let base = URL(fileURLWithPath: root).resolvingSymlinksInPath().path + "/"
88 for file in discovery.files {
89 let path = file.url.path
90 let resolved = file.url.resolvingSymlinksInPath().path
91 let relative = resolved.hasPrefix(base) ? String(resolved.dropFirst(base.count)) : file.url.lastPathComponent
92 found.append((path, relative, file.kind))
93 }
94 }
95 scanned = found
96 return found
97 }
98
99 /// `(org-agenda-files)`: `org-agenda-files` resolved, or when it is empty the org files at
100 /// the top of each folder, or below it with `agenda-include-subfolders`.
101 var agendaFiles: [String] {
102 let list = OrgPreferences.agendaFiles(defaults)
103 if !list.isEmpty { return AgendaFiles.resolve(list, base: roots.first) }
104 let subfolders = OrgPreferences.agendaSubfolders(defaults)
105 return files
106 .filter { $0.kind == .org && !($0.path as NSString).lastPathComponent.hasPrefix(".") && (subfolders || !$0.relative.contains("/")) }
107 .map(\.path)
108 .sorted()
109 }
110
111 /// The text of the file at `path`.
112 func text(_ path: String) throws(Failure) -> String {
113 guard let data = FileManager.default.contents(atPath: path) else {
114 let name = (path as NSString).lastPathComponent
115 if FileManager.default.fileExists(atPath: path) { throw Failure(.failure, "Can't read \(name)") }
116 throw Failure(.notFound, "No such file: \(path)")
117 }
118 return SourceText(bytes: [UInt8](data)).text
119 }
120
121 /// The settings for `text`, the file at `path`, with its setup files.
122 func settings(for text: String, path: String) -> OrgSettings {
123 settings.resolvingSetupFiles(in: text, path: path, read: OrgSettings.readFile)
124 }
125
126 // MARK: - Changing files
127
128 /// Runs `command` at `offset` in the file at `path` and writes the file as the app saves a
129 /// file that isn't open: through a temporary file, merged with a change made meanwhile,
130 /// the versions it replaces kept in the recovery folder as the app keeps them. The
131 /// command's result and the text after it.
132 @discardableResult
133 func perform(_ command: any OrgCommand, path: String, at offset: Int) throws(Failure) -> (result: EditResult, text: String) {
134 let url = URL(fileURLWithPath: path)
135 let name = url.lastPathComponent
136 guard !path.hasSuffix(".gpg") else { throw Failure(.refused, "\(name) is encrypted; change it in orgstar.") }
137 let fileSystem = CoordinatedFileSystem(writesInPlaceWhenDenied: false)
138 let bytes: [UInt8]
139 do {
140 guard let read = try fileSystem.read(url) else { throw Failure(.notFound, "No such file: \(path)") }
141 bytes = read
142 } catch let failure as Failure {
143 throw failure
144 } catch {
145 throw Failure(.failure, "Can't read \(name): \(error.localizedDescription)")
146 }
147 var state = DocumentState(bytes: bytes, defaults: settings(for: SourceText(bytes: bytes).text, path: path))
148 guard state.isEditable else { throw Failure(.refused, "\(name) isn't UTF-8, so it can't be changed.") }
149 let step: CommandStep
150 do {
151 step = try state.run(command, selection: [offset..<offset], now: host.now, calendar: host.calendar, options: options)
152 } catch {
153 throw Failure(.failure, "Can't change \(name): \(error)")
154 }
155 switch step {
156 case .commit(let result):
157 if state.isDirty { try save(&state, to: url) }
158 return (result, state.text)
159 case .failed(let message):
160 throw Failure(.failure, message)
161 case .prompt(let prompt):
162 throw Failure(.refused, "\(name): this needs an answer to \"\(prompt.message)\"; do it in orgstar.")
163 case .external:
164 throw Failure(.refused, "\(name): this needs a program orgstar runs; do it in orgstar.")
165 }
166 }
167
168 private func save(_ state: inout DocumentState, to url: URL) throws(Failure) {
169 let name = url.lastPathComponent
170 let saver = Saver(fileSystem: CoordinatedFileSystem(writesInPlaceWhenDenied: false),
171 recovery: FileRecoveryStore(directory: dataDirectory.appendingPathComponent("Recovery")))
172 do {
173 switch try saver.save(&state, to: url) {
174 case .saved, .mergedAndSaved:
175 break
176 case .conflict:
177 throw Failure(.failure, "\(name) changed on disk; nothing was changed.")
178 case .overwroteExternalChange, .changedAfterWrite:
179 host.error("orgstar: \(name) changed while it was written; the other version is kept in History.\n")
180 }
181 } catch let failure as Failure {
182 throw failure
183 } catch {
184 throw Failure(.failure, "Can't write \(name): \(error.localizedDescription)")
185 }
186 }
187
188 // MARK: - Headings
189
190 /// A heading or a whole file named on the command line.
191 struct Target {
192 let path: String
193 /// The heading's start; nil for the whole file.
194 let offset: Int?
195 let title: String?
196 }
197
198 /// `file`, `file::Heading`, `file::*Heading`, `file::#custom-id`, `file::id:ID` or `id:ID`.
199 func target(_ spec: String) throws(Failure) -> Target {
200 if spec.hasPrefix("id:"), !spec.contains("::") {
201 let id = String(spec.dropFirst(3))
202 for path in Array(Set(files.filter { $0.kind == .org }.map(\.path) + agendaFiles)).sorted() {
203 guard let text = try? text(path), text.contains(id),
204 let heading = headings(text, path: path).first(where: { $0.id == id }) else { continue }
205 return Target(path: path, offset: heading.headingRange.lowerBound, title: heading.title)
206 }
207 throw Failure(.notFound, "No heading with ID \(id)")
208 }
209 let parts = spec.components(separatedBy: "::")
210 let path = host.absolute(parts[0])
211 let text = try text(path)
212 guard parts.count > 1 else { return Target(path: path, offset: nil, title: nil) }
213 let search = parts.dropFirst().joined(separator: "::")
214 let all = headings(text, path: path)
215 let found: HeadingInfo?
216 if search.hasPrefix("id:") {
217 found = all.first { $0.id == String(search.dropFirst(3)) }
218 } else if search.hasPrefix("#") {
219 let custom = String(search.dropFirst())
220 found = all.first { $0.properties.contains { $0.key.uppercased() == "CUSTOM_ID" && $0.value == custom } }
221 } else {
222 let title = search.hasPrefix("*") ? String(search.dropFirst()) : search
223 found = all.first { $0.title == title } ?? all.first { $0.title.caseInsensitiveCompare(title) == .orderedSame }
224 }
225 guard let found else { throw Failure(.notFound, "No heading \(search) in \((path as NSString).lastPathComponent)") }
226 return Target(path: path, offset: found.headingRange.lowerBound, title: found.title)
227 }
228
229 func headings(_ text: String, path: String) -> [HeadingInfo] {
230 DocumentModel(tree: OrgParser.parse(text, defaults: settings(for: text, path: path))).headings
231 }
232
233 /// The 1-based line of `offset`, a UTF-16 offset in `text`.
234 static func line(of offset: Int, in text: String) -> Int {
235 let ns = text as NSString
236 var line = 1
237 var index = 0
238 let end = min(offset, ns.length)
239 while index < end {
240 let found = ns.range(of: "\n", options: [], range: NSRange(location: index, length: end - index))
241 guard found.location != NSNotFound else { break }
242 line += 1
243 index = found.location + 1
244 }
245 return line
246 }
247}
Sources/OrgstarCLI/main.swift added +3 · view
@@ -0,0 +1,3 @@
1import Foundation
2
3exit(Tool.run(Array(CommandLine.arguments.dropFirst()), host: .process()))
Tests/OrgAppTests/AppTests.swift +22 · view
@@ -1283,6 +1283,28 @@ struct ClockModelTests {
1283 #expect(clock.running?.start == "2026-10-05 Mon 11:00") 1283 #expect(clock.running?.start == "2026-10-05 Mon 11:00")
1284 } 1284 }
1285 1285
1286 /// Clocking in on another entry elsewhere, in the same file, stops this clock and runs that one.
1287 @Test func followsAClockSwitchedElsewhere() throws {
1288 let notes = try Folder()
1289 let work = try notes.write("work.org", "* Task\n:LOGBOOK:\nCLOCK: [2026-10-05 Mon 09:00]\n:END:\n* Next\n")
1290 let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
1291 let clock = ClockModel(file: notes.url.appendingPathComponent("clock.json"))
1292 clock.sync(session, paths: [work.path])
1293 try """
1294 * Task
1295 :LOGBOOK:
1296 CLOCK: [2026-10-05 Mon 09:00]--[2026-10-05 Mon 10:00] => 1:00
1297 :END:
1298 * Next
1299 :LOGBOOK:
1300 CLOCK: [2026-10-05 Mon 10:00]
1301 :END:
1302
1303 """.write(to: work, atomically: true, encoding: .utf8)
1304 #expect(clock.sync(session, paths: [work.path]) == "Clock running in \"Next\" since [2026-10-05 Mon 10:00]")
1305 #expect(clock.running?.start == "2026-10-05 Mon 10:00")
1306 }
1307
1286 @Test func clocksInAndOutAcrossFiles() throws { 1308 @Test func clocksInAndOutAcrossFiles() throws {
1287 let notes = try Folder() 1309 let notes = try Folder()
1288 let work = try notes.write("work.org", "* Task\nBody\n") 1310 let work = try notes.write("work.org", "* Task\nBody\n")
Tests/OrgAppTests/TangleWriterTests.swift +1 · view
@@ -1,6 +1,7 @@
1import Foundation 1import Foundation
2import Testing 2import Testing
3@testable import OrgApp 3@testable import OrgApp
4@testable import OrgConfig
4@testable import OrgCore 5@testable import OrgCore
5 6
6struct TangleWriterTests { 7struct TangleWriterTests {
Tests/OrgProgramsTests/CommandLineToolTests.swift added +40 · view
@@ -0,0 +1,40 @@
1import Foundation
2import Testing
3import OrgPrograms
4
5struct CommandLineToolTests {
6 @Test func linksTheHelperAndReplacesALink() throws {
7 let folder = try Folder()
8 let app = folder.url.appendingPathComponent("orgstar.app")
9 let helper = try folder.write("orgstar.app/Contents/Helpers/orgstar", "#!/bin/sh\n")
10 try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: helper.path)
11 #expect(CommandLineTool.helper(in: app) == helper)
12 let bin = folder.url.appendingPathComponent("bin")
13 try FileManager.default.createDirectory(at: bin, withIntermediateDirectories: true)
14 try FileManager.default.createSymbolicLink(atPath: bin.appendingPathComponent("orgstar").path, withDestinationPath: "/old/orgstar")
15 let link = try CommandLineTool.install(helper, in: bin)
16 #expect(link == bin.appendingPathComponent("orgstar"))
17 #expect(try FileManager.default.destinationOfSymbolicLink(atPath: link.path) == helper.path)
18 #expect(try FileManager.default.contentsOfDirectory(atPath: bin.path) == ["orgstar"])
19 }
20
21 @Test func leavesOtherFilesAndReportsWhy() throws {
22 let folder = try Folder()
23 let helper = try folder.write("orgstar.app/Contents/Helpers/orgstar", "#!/bin/sh\n")
24 try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: helper.path)
25 let file = try folder.write("bin/orgstar", "mine")
26 #expect(throws: CommandLineTool.Failure.occupied(path: file.path)) { try CommandLineTool.install(helper, in: file.deletingLastPathComponent()) }
27 #expect(try String(contentsOf: file, encoding: .utf8) == "mine")
28 #expect(throws: CommandLineTool.Failure.missing) { try CommandLineTool.install(folder.url.appendingPathComponent("none"), in: folder.url) }
29 let locked = folder.url.appendingPathComponent("locked")
30 try FileManager.default.createDirectory(at: locked, withIntermediateDirectories: true)
31 try FileManager.default.setAttributes([.posixPermissions: 0o555], ofItemAtPath: locked.path)
32 defer { try? FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: locked.path) }
33 #expect {
34 try CommandLineTool.install(helper, in: locked)
35 } throws: { error in
36 guard case .unwritable(let path, _) = error as? CommandLineTool.Failure else { return false }
37 return path == locked.path
38 }
39 }
40}
Tests/OrgstarCLITests/ToolTests.swift added +323 · view
@@ -0,0 +1,323 @@
1import Foundation
2import Testing
3@testable import OrgstarCLI
4
5/// A configuration folder, a data folder and a folder of notes in a temporary folder, and the
6/// tool run over them at a fixed time.
7@MainActor
8final class Sandbox {
9 let folder: URL
10 let config: URL
11 let data: URL
12 let notes: URL
13 var now: Date
14 var calendar: Calendar
15 var opened: [[String]] = []
16
17 init() throws {
18 folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-cli-\(UUID().uuidString)").resolvingSymlinksInPath()
19 config = folder.appendingPathComponent("config")
20 data = folder.appendingPathComponent("data")
21 notes = folder.appendingPathComponent("notes")
22 for url in [config, data, notes] { try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true) }
23 calendar = Calendar(identifier: .gregorian)
24 calendar.timeZone = TimeZone(identifier: "UTC")!
25 // Thursday 26 November 2026, 10:00.
26 now = calendar.date(from: DateComponents(year: 2026, month: 11, day: 26, hour: 10))!
27 }
28
29 deinit { try? FileManager.default.removeItem(at: folder) }
30
31 func write(_ text: String, _ name: String, in folder: URL? = nil) throws {
32 let url = (folder ?? notes).appendingPathComponent(name)
33 try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)
34 try text.write(to: url, atomically: true, encoding: .utf8)
35 }
36
37 func read(_ name: String) throws -> String {
38 try String(contentsOf: notes.appendingPathComponent(name), encoding: .utf8)
39 }
40
41 func run(_ arguments: String..., input: String? = nil, environment: [String: String] = [:]) -> (status: Int32, out: String, err: String) {
42 var out = Data()
43 var err = ""
44 var host = Host(
45 environment: ["ORGSTAR_CONFIG_DIR": config.path, "ORGSTAR_DATA_DIR": data.path, "ORGSTAR_ROOT": notes.path, "PATH": folder.path]
46 .merging(environment) { $1 },
47 now: now, calendar: calendar, currentDirectory: notes.path,
48 input: { input }, output: { out.append($0) }, error: { err += $0 }, open: { _ in 0 },
49 executable: folder.appendingPathComponent("orgstar")
50 )
51 host.open = { [weak self] arguments in
52 self?.opened.append(arguments)
53 return 0
54 }
55 let status = Tool.run(arguments, host: host)
56 return (status, String(decoding: out, as: UTF8.self), err)
57 }
58}
59
60@MainActor
61struct AgendaTests {
62 static let tasks = """
63 #+TITLE: Tasks
64 * TODO Write report
65 SCHEDULED: <2026-11-26 Thu>
66 * TODO Pay rent :home:
67 DEADLINE: <2026-11-27 Fri>
68 * TODO Call Sam
69 * DONE Old thing
70 """
71
72 @Test func printsTheDayAsEmacsDoes() throws {
73 let sandbox = try Sandbox()
74 try sandbox.write("org-agenda-span = 1\n", "config.toml", in: sandbox.config)
75 try sandbox.write(Self.tasks, "tasks.org")
76 let (status, out, err) = sandbox.run("agenda")
77 #expect(status == 0, "\(err)")
78 let lines = out.split(separator: "\n").map(String.init)
79 #expect(lines.first == "Day-agenda (W48):")
80 #expect(lines.contains("Thursday 26 November 2026"))
81 #expect(lines.contains { $0.hasPrefix(" tasks:") && $0.hasSuffix("Scheduled: TODO Write report") })
82 #expect(lines.contains { $0.contains("In 1 d.: TODO Pay rent") && $0.hasSuffix(":home:") })
83 #expect(!out.contains("Call Sam"))
84 }
85
86 @Test func listsAViewAsJSONWithLines() throws {
87 let sandbox = try Sandbox()
88 try sandbox.write(Self.tasks, "tasks.org")
89 let (status, out, _) = sandbox.run("agenda", "todo list", "--json")
90 #expect(status == 0)
91 let json = try #require(try JSONSerialization.jsonObject(with: Data(out.utf8)) as? [String: Any])
92 #expect(json["view"] as? String == "TODO List")
93 let block = try #require((json["blocks"] as? [[String: Any]])?.first)
94 #expect(block["type"] as? String == "todo")
95 let entries = try #require(block["entries"] as? [[String: Any]])
96 #expect(entries.map { $0["title"] as? String } == ["TODO Write report", "TODO Pay rent", "TODO Call Sam"])
97 #expect(entries.map { $0["line"] as? Int } == [2, 4, 6])
98 #expect(entries[1]["tags"] as? [String] == ["home"])
99 #expect(entries[0]["file"] as? String == sandbox.notes.appendingPathComponent("tasks.org").path)
100 }
101
102 @Test func runsAViewOfViewsToml() throws {
103 let sandbox = try Sandbox()
104 try sandbox.write(Self.tasks, "tasks.org")
105 try sandbox.write("[[view]]\nname = \"Home\"\ntype = \"match\"\nmatch = \"home\"\n", "views.toml", in: sandbox.config)
106 let (status, out, _) = sandbox.run("agenda", "Home")
107 #expect(status == 0)
108 #expect(out.hasPrefix("Headlines with TAGS match: home\n"))
109 #expect(out.contains("TODO Pay rent"))
110 #expect(!out.contains("Write report"))
111 let missing = sandbox.run("agenda", "Nope")
112 #expect(missing.status == 3)
113 #expect(missing.err.contains("No agenda view named Nope"))
114 }
115}
116
117@MainActor
118struct CaptureTests {
119 static let templates = """
120 [[template]]
121 key = "t"
122 name = "Todo"
123 file = "inbox.org"
124 headline = "Inbox"
125 template = "* TODO %?%i"
126
127 [[template]]
128 key = "m"
129 name = "Meeting"
130 file = "inbox.org"
131 headline = "Meetings"
132 template = "* %^{Who} %^{Where|office}\\n%i"
133 """
134
135 @Test func filesTheTextUnderTheHeadline() throws {
136 let sandbox = try Sandbox()
137 try sandbox.write(Self.templates, "capture.toml", in: sandbox.config)
138 try sandbox.write("* Inbox\n* Meetings\n", "inbox.org")
139 let (status, out, err) = sandbox.run("capture", "t", "Buy milk")
140 #expect(status == 0, "\(err)")
141 #expect(out == "Captured to \(sandbox.notes.appendingPathComponent("inbox.org").path):2\n")
142 #expect(try sandbox.read("inbox.org") == "* Inbox\n** TODO Buy milk\n* Meetings\n")
143 let piped = sandbox.run("capture", "t", input: "Call the bank\n")
144 #expect(piped.status == 0)
145 #expect(try sandbox.read("inbox.org") == "* Inbox\n** TODO Buy milk\n** TODO Call the bank\n* Meetings\n")
146 }
147
148 @Test func refusesQuestionsWithoutAnswers() throws {
149 let sandbox = try Sandbox()
150 try sandbox.write(Self.templates, "capture.toml", in: sandbox.config)
151 try sandbox.write("* Inbox\n* Meetings\n", "inbox.org")
152 let refused = sandbox.run("capture", "m", "Notes")
153 #expect(refused.status == 4)
154 #expect(refused.err.contains("asks \"Who\""))
155 #expect(try sandbox.read("inbox.org") == "* Inbox\n* Meetings\n")
156 let answered = sandbox.run("capture", "m", "Notes", "--set", "Who=Sam")
157 #expect(answered.status == 0, "\(answered.err)")
158 #expect(try sandbox.read("inbox.org") == "* Inbox\n* Meetings\n** Sam office\nNotes\n")
159 }
160
161 @Test func createsAMissingFileAndNamesUnknownTemplates() throws {
162 let sandbox = try Sandbox()
163 try sandbox.write("[[template]]\nkey = \"j\"\nname = \"Journal\"\nfile = \"journal/log.org\"\ntemplate = \"* %i\"\n", "capture.toml", in: sandbox.config)
164 #expect(sandbox.run("capture", "j", "First").status == 0)
165 #expect(try sandbox.read("journal/log.org") == "* First\n")
166 let unknown = sandbox.run("capture", "x", "text")
167 #expect(unknown.status == 3)
168 #expect(unknown.err.contains("j (Journal)"))
169 }
170}
171
172@MainActor
173struct ClockTests {
174 @Test func clocksInAndOutAndSwitches() throws {
175 let sandbox = try Sandbox()
176 try sandbox.write("* Report\n* Email\n", "work.org")
177 #expect(sandbox.run("clock", "status").status == 3)
178 let clockIn = sandbox.run("clock", "in", "work.org::Report")
179 #expect(clockIn.status == 0, "\(clockIn.err)")
180 #expect(clockIn.out == "Clock starts at [2026-11-26 Thu 10:00] in \"Report\"\n")
181 #expect(try sandbox.read("work.org") == "* Report\n:LOGBOOK:\nCLOCK: [2026-11-26 Thu 10:00]\n:END:\n* Email\n")
182
183 sandbox.now += 25 * 60
184 let status = sandbox.run("clock", "status", "--json")
185 let json = try #require(try JSONSerialization.jsonObject(with: Data(status.out.utf8)) as? [String: Any])
186 let running = try #require(json["running"] as? [String: Any])
187 #expect(running["heading"] as? String == "Report")
188 #expect(running["minutes"] as? Int == 25)
189
190 sandbox.now += 5 * 60
191 let switched = sandbox.run("clock", "in", "work.org::*Email")
192 #expect(switched.status == 0, "\(switched.err)")
193 #expect(switched.out == "Clock stopped after 0:30 in \"Report\"\nClock starts at [2026-11-26 Thu 10:30] in \"Email\"\n")
194
195 sandbox.now += 60 * 60
196 let out = sandbox.run("clock", "out")
197 #expect(out.out == "Clock stopped after 1:00 in \"Email\"\n")
198 #expect(try sandbox.read("work.org") == """
199 * Report
200 :LOGBOOK:
201 CLOCK: [2026-11-26 Thu 10:00]--[2026-11-26 Thu 10:30] => 0:30
202 :END:
203 * Email
204 :LOGBOOK:
205 CLOCK: [2026-11-26 Thu 10:30]--[2026-11-26 Thu 11:30] => 1:00
206 :END:
207
208 """)
209 let none = sandbox.run("clock", "out")
210 #expect(none.status == 3)
211 #expect(none.err == "orgstar: No active clock\n")
212 }
213
214 @Test func clocksInByID() throws {
215 let sandbox = try Sandbox()
216 try sandbox.write("* Report\n:PROPERTIES:\n:ID: abc-123\n:END:\n", "work.org")
217 #expect(sandbox.run("clock", "in", "id:abc-123").status == 0)
218 #expect(try sandbox.read("work.org").contains(":END:\n:LOGBOOK:\nCLOCK: [2026-11-26 Thu 10:00]\n:END:\n"))
219 #expect(sandbox.run("clock", "in", "work.org::Nothing").status == 3)
220 }
221
222 @Test func keepsAVersionInRecovery() throws {
223 let sandbox = try Sandbox()
224 try sandbox.write("* Report\n", "work.org")
225 #expect(sandbox.run("clock", "in", "work.org::Report").status == 0)
226 let recovery = sandbox.data.appendingPathComponent("Recovery")
227 let kept = try FileManager.default.subpathsOfDirectory(atPath: recovery.path).filter { $0.hasSuffix("work.org") }
228 #expect(kept.count == 1)
229 }
230}
231
232@MainActor
233struct ExportTests {
234 static let text = "#+TITLE: Notes\n* One\nSome *bold* text.\n"
235
236 @Test func exportsBesideTheFile() throws {
237 let sandbox = try Sandbox()
238 try sandbox.write(Self.text, "notes.org")
239 for (format, ext, contains) in [("html", "html", "<strong>bold</strong>"), ("md", "md", "**bold**"), ("latex", "tex", "\\textbf{bold}"), ("txt", "txt", "*bold*"), ("reveal", "html", "One")] {
240 let (status, out, err) = sandbox.run("export", "notes.org", "--to", format)
241 #expect(status == 0, "\(format): \(err)")
242 let path = sandbox.notes.appendingPathComponent("notes.\(ext)").path
243 #expect(out == "Exported to \(path)\n")
244 #expect(try String(contentsOfFile: path, encoding: .utf8).contains(contains), "\(format)")
245 }
246 #expect(sandbox.run("export", "notes.org", "--to", "odt", "-o", "out/notes.odt").status == 0)
247 let odt = try Data(contentsOf: sandbox.notes.appendingPathComponent("out/notes.odt"))
248 #expect(odt.prefix(2) == Data("PK".utf8))
249 }
250
251 @Test func writesToStandardOutput() throws {
252 let sandbox = try Sandbox()
253 try sandbox.write(Self.text, "notes.org")
254 let (status, out, _) = sandbox.run("export", "notes.org", "--to=md", "-o", "-")
255 #expect(status == 0)
256 #expect(out.contains("# One"))
257 #expect(!FileManager.default.fileExists(atPath: sandbox.notes.appendingPathComponent("notes.md").path))
258 }
259
260 @Test(.enabled(if: !FileManager.default.fileExists(atPath: "/Library/TeX/texbin/pdflatex"))) func pdfWithoutTeXSaysWhatItNeeds() throws {
261 let sandbox = try Sandbox()
262 try sandbox.write(Self.text, "notes.org")
263 let (status, _, err) = sandbox.run("export", "notes.org", "--to", "pdf")
264 #expect(status == 1)
265 #expect(err.contains("needs TeX"))
266 }
267
268 @Test func tanglesBlocks() throws {
269 let sandbox = try Sandbox()
270 try sandbox.write("* Script\n#+begin_src sh :tangle out/run.sh :mkdirp yes\necho hi\n#+end_src\n", "code.org")
271 let (status, out, err) = sandbox.run("tangle", "code.org")
272 #expect(status == 0, "\(err)")
273 #expect(out == "Tangled 1 code block from code.org\n")
274 #expect(try sandbox.read("out/run.sh") == "echo hi\n")
275 }
276}
277
278@MainActor
279struct ArgumentTests {
280 @Test func usageErrorsExitWithTwo() throws {
281 let sandbox = try Sandbox()
282 try sandbox.write("* A\n", "a.org")
283 #expect(sandbox.run().status == 2)
284 #expect(sandbox.run("frobnicate").status == 2)
285 #expect(sandbox.run("agenda", "--bogus").status == 2)
286 #expect(sandbox.run("agenda", "one", "two").status == 2)
287 #expect(sandbox.run("export", "a.org").status == 2)
288 #expect(sandbox.run("export", "a.org", "--to", "doc").status == 2)
289 #expect(sandbox.run("export", "a.org", "--to").status == 2)
290 #expect(sandbox.run("capture").status == 2)
291 #expect(sandbox.run("capture", "t", "x", "--set", "novalue").status == 2)
292 #expect(sandbox.run("clock").status == 2)
293 #expect(sandbox.run("clock", "in").status == 2)
294 #expect(sandbox.run("clock", "in", "a.org").status == 2)
295 #expect(sandbox.run("export", "missing.org", "--to", "md").status == 3)
296 }
297
298 @Test func helpAndVersion() throws {
299 let sandbox = try Sandbox()
300 let help = sandbox.run("--help")
301 #expect(help.status == 0)
302 #expect(help.out.contains("Exit status:"))
303 for command in ["agenda", "capture", "clock", "export", "tangle", "open"] {
304 let result = sandbox.run(command, "--help")
305 #expect(result.status == 0)
306 #expect(result.out.hasPrefix("Usage: orgstar \(command)"))
307 }
308 #expect(sandbox.run("help", "clock").out.hasPrefix("Usage: orgstar clock"))
309 #expect(sandbox.run("--version").out == "orgstar (development build)\n")
310 }
311
312 @Test func opensTheEntryInTheApp() throws {
313 let sandbox = try Sandbox()
314 try sandbox.write("* A\n* B\n", "a.org")
315 #expect(sandbox.run("open", "a.org::B").status == 0)
316 let path = sandbox.notes.appendingPathComponent("a.org").path
317 var link = URLComponents()
318 link.scheme = "orgstar"
319 link.host = "entry"
320 link.queryItems = [URLQueryItem(name: "path", value: path), URLQueryItem(name: "offset", value: "4")]
321 #expect(sandbox.opened == [[link.url!.absoluteString]])
322 }
323}
docs/manual/guide/13-configuration.org +2 −1 · view
@@ -25,7 +25,7 @@ The folder holds these files:
25| =snippets.toml= | Snippets and templates for new files | Only by Import from Emacs | 25| =snippets.toml= | Snippets and templates for new files | Only by Import from Emacs |
26| =default-theme.toml= | The default theme's colors, for reference | Yes, at every launch | 26| =default-theme.toml= | The default theme's colors, for reference | Yes, at every launch |
27 27
28=config.toml= is the source of truth. The Settings window writes each change into it, keeping your comments and the order of lines, and edits you make to the file apply while orgstar runs. If the file doesn't exist at launch, orgstar creates it with every setting at its current value and a comment after each one. A file that is there but can't be read, such as one that isn't UTF-8, is left as it is: the change isn't written and a message says why, as it does when a write fails. Import from Emacs and saving an agenda view treat =capture.toml=, =views.toml= and =keymap.toml= the same way. 28=config.toml= is the source of truth. The Settings window writes each change into it, keeping your comments and the order of lines, and edits you make to the file apply while orgstar runs. The [[file:17-command-line.org][orgstar command]] reads the same folder, =ORGSTAR_CONFIG_DIR= included. If the file doesn't exist at launch, orgstar creates it with every setting at its current value and a comment after each one. A file that is there but can't be read, such as one that isn't UTF-8, is left as it is: the change isn't written and a message says why, as it does when a write fails. Import from Emacs and saving an agenda view treat =capture.toml=, =views.toml= and =keymap.toml= the same way.
29 29
30When you add the folder to a dotfiles repository, keep =default-theme.toml= out of it or ignore its changes: orgstar rewrites it whenever its contents differ from the built-in theme. 30When you add the folder to a dotfiles repository, keep =default-theme.toml= out of it or ignore its changes: orgstar rewrites it whenever its contents differ from the built-in theme.
31 31
@@ -61,6 +61,7 @@ Open it with orgstar ▸ Settings (=⌘,=). It has seven panes, and an eighth, G
61| Folder: Choose Configuration Folder… | Mac App Store version: reads and writes the configuration in a folder you choose | | | 61| Folder: Choose Configuration Folder… | Mac App Store version: reads and writes the configuration in a folder you choose | | |
62| Folder: Use Default Folder | Mac App Store version: goes back to the folder in the app's container | | | 62| Folder: Use Default Folder | Mac App Store version: goes back to the folder in the app's container | | |
63| Emacs: Import from Emacs… | Opens the import sheet; see Import from Emacs below| | | 63| Emacs: Import from Emacs… | Opens the import sheet; see Import from Emacs below| | |
64| Command line: Install Command-Line Tool… | Download version: links the =orgstar= command into a folder you choose; see [[file:17-command-line.org][The command line]] | | |
64| Check for updates automatically | Download version: once a day; orgstar ▸ Check for Updates… checks now | Asked on the second launch | | 65| Check for updates automatically | Download version: once a day; orgstar ▸ Check for Updates… checks now | Asked on the second launch | |
65| Save files | Automatically, when typing stops; Only with File ▸ Save (=⌘S=) | Automatically | =save= | 66| Save files | Automatically, when typing stops; Only with File ▸ Save (=⌘S=) | Automatically | =save= |
66| Keys | Emacs; Mac; Doom (Vim keys) | Emacs | =keymap= | 67| Keys | Emacs; Mac; Doom (Vim keys) | Emacs | =keymap= |
docs/manual/guide/17-command-line.org added +122 · view
@@ -0,0 +1,122 @@
1#+TITLE: The command line
2#+DESCRIPTION: The orgstar command: the agenda as text or JSON, capture, clocking in and out, export, tangling and opening a file in the app, from Terminal and scripts.
3#+LEDE: The download version comes with an orgstar command that works on your files with the app's configuration, whether or not the app is running.
4
5* Installing the command
6
7The command is inside the app, at =orgstar.app/Contents/Helpers/orgstar=. To run it as =orgstar=:
8
9- Settings ▸ General ▸ Install Command-Line Tool… asks for a folder on your =PATH= and puts a link to the command there. =~/.local/bin= needs no administrator password; =/usr/local/bin= works when you can write to it. When orgstar can't write in the folder, the alert gives the =sudo ln -sf …= line to run in Terminal instead.
10- The Homebrew cask links it as =orgstar= when it installs the app.
11- A build from source has it at =.build/app/orgstar.app/Contents/Helpers/orgstar=.
12
13The link points into the app, so updating the app updates the command. The Mac App Store version has no command: its sandbox can't reach your files from another program.
14
15* What it reads
16
17The command reads the files the app reads and changes them the way the app does:
18
19- The configuration folder (see [[file:13-configuration.org][Configuration]]): =config.toml= for the settings, =capture.toml= for capture templates and =views.toml= for agenda views. Problems in them are printed as warnings.
20- The folders added in the app (File ▸ Add Folder…), from the app's data folder, =~/Library/Application Support/Orgstar=. =org-agenda-files= in =config.toml= chooses the agenda files as in the app.
21- Each file's own settings and =#+SETUPFILE:=.
22
23It doesn't need the app to be running. Choices kept only in the app are not read: folders hidden from the agenda, Calendar events and Reminders in the agenda, and each file's export choices.
24
25| Variable | What it sets |
26|-----------------------+------------------------------------------------------------------------------------------------------|
27| =ORGSTAR_CONFIG_DIR= | The configuration folder, instead of =$XDG_CONFIG_HOME/orgstar= or =~/.config/orgstar= |
28| =ORGSTAR_DATA_DIR= | The data folder, which holds the folder list, the running clock and recovery versions |
29| =ORGSTAR_ROOT= | A folder to read besides those added in the app |
30
31* Commands
32
33=orgstar --help= lists the commands, and =orgstar <command> --help= describes one. =orgstar --version= prints the app's version.
34
35** agenda
36
37#+BEGIN_SRC sh
38orgstar agenda
39orgstar agenda "TODO List"
40orgstar agenda Work --json
41#+END_SRC
42
43Prints the agenda as Emacs's agenda buffer shows it, with the span and start of Settings ▸ Agenda, the prefix format, sorting and time grid of =config.toml=. A name prints that view instead: TODO List, Stuck Projects, or a =[[view]]= of =views.toml=, block views included.
44
45#+BEGIN_EXAMPLE
46Week-agenda (W48):
47Friday 27 November 2026
48 8:00...... ----------------
49 tasks: 14:00-15:00 Meeting with Sam
50 tasks: Scheduled: TODO Write report
51 tasks: In 3 d.: TODO Pay rent :home:
52#+END_EXAMPLE
53
54=--json= prints the view's blocks, each with its header and its days and entries. An entry has its file, line and offset, category, keyword, title, tags, time and leader (=extra=), and the line as the text shows it.
55
56** capture
57
58#+BEGIN_SRC sh
59orgstar capture t "Buy milk"
60pbpaste | orgstar capture n
61orgstar capture m "Agenda for Monday" --set Who=Sam
62#+END_SRC
63
64Files an entry with the template of =capture.toml= that has that key, at once, as Shortcuts' Capture to Orgstar does. The text is =%i=: the argument, or standard input when there is none. =%?= is dropped.
65
66Questions are answered with =--set Prompt=value=, by the prompt's text: =%^{Who}= by =--set Who=…=. A question with a default (=%^{Room|Office}=) takes it when not set. A question with neither stops the capture with exit status 4 and names what to set, and nothing is written. Unset, =%^g= and =%^G= add no tags and the date questions take today; set them with =--set Tags=work:urgent= or =--set Date=+2d=. =%a=, =%c=, =%x= and =%f= are empty, since there's no buffer or clipboard. =%k= and =%K= are the running clock's entry.
67
68Targets work as in the app: a file is made when missing, =id= finds the heading in your folders, =clock= files under the running clock. =clock-in= with =clock-keep= starts the clock on the new entry; without =clock-keep= there's nothing to time, since the capture finishes at once. Templates with =denote = true= are refused; use them in the app.
69
70** clock
71
72#+BEGIN_SRC sh
73orgstar clock in work.org::"Write report"
74orgstar clock in id:0F3C2A1E-6B8D-4E3A-9B4F-2D1C0A9E8B7F
75orgstar clock status
76orgstar clock out
77#+END_SRC
78
79=clock in= starts the clock on a heading, named by its title (with or without a leading =*=), =#custom-id= or =id:ID=, after the file and =::=; =id:ID= alone looks in every folder. A running clock is clocked out first, as =org-clock-in= does. =clock out= stops the running clock. =clock status= prints the running clock, or with =--json= an object whose =running= is the clock or =null=; it exits with 3 when no clock runs.
80
81The command writes only the org file: the =CLOCK:= line, in the =LOGBOOK= drawer when =org-clock-into-drawer= says so, with the switch to =org-clock-in-switch-to-state= and the rounding and zero-time settings of =config.toml=. The running clock is the one the app shows when its line is still open, else the most recently started open =CLOCK:= line in the agenda files. The app watches your folders, so a clock started or stopped from the command line shows in the app as one started or stopped in Emacs does; the app's own record of the clock is never written by the command, so the two never write the same file.
82
83** export and tangle
84
85#+BEGIN_SRC sh
86orgstar export notes.org --to html
87orgstar export notes.org --to md -o -
88orgstar export notes.org --to odt -o ~/Desktop/notes.odt
89orgstar tangle init.org
90#+END_SRC
91
92Exports the whole file as File ▸ Export does, to =html=, =md=, =latex=, =txt=, =odt=, =reveal= or =pdf=, beside the file and named by =#+EXPORT_FILE_NAME= or the file's name, or to the path =-o= gives; =-o -= writes to standard output. Code in the HTML export isn't coloured. =pdf= runs the LaTeX export through =latexmk=, or =pdflatex= three times, as Emacs's =org-latex-export-to-pdf= does, so it needs TeX, such as MacTeX; the app's own PDF export doesn't.
93
94=tangle= writes the file's code blocks with =:tangle= to their files, as Tangle File (=C-c C-v t=) does, from the file as saved.
95
96** open
97
98#+BEGIN_SRC sh
99orgstar open notes.org
100orgstar open notes.org::"Reading list"
101orgstar open id:0F3C2A1E-6B8D-4E3A-9B4F-2D1C0A9E8B7F
102#+END_SRC
103
104Opens the file in orgstar, at the heading when one is named, through the app's =orgstar://entry= link. It starts orgstar when it isn't running.
105
106* How files are written
107
108The command saves a file the way the app saves one that isn't open: through a temporary file that replaces it, merged with any change made since it was read, and with the version it replaces kept for File ▸ History… as the app keeps them. Encrypted =.org.gpg= files and files that aren't UTF-8 are refused.
109
110There's no lock between the app and the command. A file open in orgstar takes in the command's change as it takes in one from Emacs: merged into the buffer, unsaved edits included, or shown as a conflict to resolve when both changed the same lines.
111
112* Exit status
113
114| Status | Meaning |
115|--------+--------------------------------------------------------------------------------------------------------------|
116| 0 | Done |
117| 1 | Failed: a file couldn't be read, written or exported, or it changed while being written |
118| 2 | Usage: an unknown command or option, or a missing argument |
119| 3 | Not found: no such file, heading, view or template; no running clock |
120| 4 | Refused: a capture question without an answer, or a file or command that needs the app |
121
122Messages go to standard error, prefixed with =orgstar:=.
docs/manual/index.org +1 · view
@@ -37,6 +37,7 @@ reminders, export and tangling.
3714. [[file:guide/14-ios.org][iPhone and iPad]] 3714. [[file:guide/14-ios.org][iPhone and iPad]]
3815. [[file:guide/15-alongside-emacs.org][Working alongside Emacs and other tools]] 3815. [[file:guide/15-alongside-emacs.org][Working alongside Emacs and other tools]]
3916. [[file:guide/16-flashcards.org][Flashcards]] 3916. [[file:guide/16-flashcards.org][Flashcards]]
4017. [[file:guide/17-command-line.org][The command line]]
40 41
41* Principles 42* Principles
42 43
docs/manual/install.org +9 −2 · view
@@ -21,7 +21,7 @@ differ in where they come from, how orgstar+ is bought, and what they can run.
21 with the iPhone and iPad app. 21 with the iPhone and iPad app.
22- The download version, from Homebrew or files.krz.sh, is signed with a Developer ID and 22- The download version, from Homebrew or files.krz.sh, is signed with a Developer ID and
23 notarized. It runs code blocks with the programs installed on the Mac, hands some tables and 23 notarized. It runs code blocks with the programs installed on the Mac, hands some tables and
24 exports to Emacs, and updates itself. 24 exports to Emacs, has an =orgstar= command for Terminal, and updates itself.
25 25
26** From the Mac App Store 26** From the Mac App Store
27 27
@@ -38,6 +38,8 @@ brew tap krz/tap https://gitbay.org/krz/homebrew-tap.git
38brew install --cask orgstar 38brew install --cask orgstar
39#+END_SRC 39#+END_SRC
40 40
41The cask also links the =orgstar= command into Homebrew's =bin= folder; see [[file:guide/17-command-line.org][The command line]].
42
41** As a download 43** As a download
42 44
43Download the newest =orgstar-<version>.dmg= from [[https://files.krz.sh/orgstar/][files.krz.sh/orgstar]], open it, and drag 45Download the newest =orgstar-<version>.dmg= from [[https://files.krz.sh/orgstar/][files.krz.sh/orgstar]], open it, and drag
@@ -48,6 +50,9 @@ Once the app has been launched, Finder opens =.org= files with it, Quick Look sh
48them formatted, and Spotlight indexes their headings and text. The same is true of the Mac 50them formatted, and Spotlight indexes their headings and text. The same is true of the Mac
49App Store version. 51App Store version.
50 52
53To use the =orgstar= command in Terminal, click Settings ▸ General ▸ Install Command-Line
54Tool… and choose a folder on your =PATH=, such as =~/.local/bin=. See [[file:guide/17-command-line.org][The command line]].
55
51* The Mac App Store version 56* The Mac App Store version
52 57
53** What it does differently 58** What it does differently
@@ -64,6 +69,7 @@ App Store version.
64| Files outside your folders | After you grant access to their folder | Directly | 69| Files outside your folders | After you grant access to their folder | Directly |
65| Attachments | Copied, or moved from inside your folders | Copied, moved, linked or symlinked | 70| Attachments | Copied, or moved from inside your folders | Copied, moved, linked or symlinked |
66| Git | No | Commits as you save, with pull and push; commits in File ▸ History… | 71| Git | No | Commits as you save, with pull and push; commits in File ▸ History… |
72| Command line | No | The =orgstar= command: agenda, capture, clock, export, tangle, open |
67| Updates | The Mac App Store | Built in, or Homebrew | 73| Updates | The Mac App Store | Built in, or Homebrew |
68| orgstar+ | In-app purchase, shared with iPhone and iPad | License key | 74| orgstar+ | In-app purchase, shared with iPhone and iPad | License key |
69 75
@@ -166,7 +172,8 @@ What's New in orgstar shows them again, in both versions.
166 172
167* Uninstalling 173* Uninstalling
168 174
169Delete =orgstar.app=, or run =brew uninstall --cask orgstar=. To remove your settings as 175Delete =orgstar.app=, or run =brew uninstall --cask orgstar=, and the =orgstar= link if you
176installed the command from Settings, such as =~/.local/bin/orgstar=. To remove your settings as
170well, delete =~/.config/orgstar/= (=brew uninstall --zap --cask orgstar= does both). The App 177well, delete =~/.config/orgstar/= (=brew uninstall --zap --cask orgstar= does both). The App
171Store version keeps its settings, index and recovery versions in 178Store version keeps its settings, index and recovery versions in
172=~/Library/Containers/sh.krz.orgstar/=, and the widgets' data in 179=~/Library/Containers/sh.krz.orgstar/=, and the widgets' data in
l10n/DeveloperID.xcstrings +374 · view
@@ -1,6 +1,74 @@
1{ 1{
2 "sourceLanguage": "en", 2 "sourceLanguage": "en",
3 "strings": { 3 "strings": {
4 "%@ is already there and isn't a link. Move it away or choose another folder.": {
5 "localizations": {
6 "de": {
7 "stringUnit": {
8 "state": "translated",
9 "value": "%@ existiert bereits und ist kein Link. Verschiebe die Datei oder wähle einen anderen Ordner."
10 }
11 },
12 "es": {
13 "stringUnit": {
14 "state": "translated",
15 "value": "%@ ya existe y no es un enlace. Muévelo o elige otra carpeta."
16 }
17 },
18 "fr": {
19 "stringUnit": {
20 "state": "translated",
21 "value": "%@ existe déjà et n’est pas un lien. Déplacez-le ou choisissez un autre dossier."
22 }
23 },
24 "ja": {
25 "stringUnit": {
26 "state": "translated",
27 "value": "%@ はすでに存在し、リンクではありません。移動するか、別のフォルダを選んでください。"
28 }
29 },
30 "pt-BR": {
31 "stringUnit": {
32 "state": "translated",
33 "value": "%@ já existe e não é um link. Mova-o ou escolha outra pasta."
34 }
35 }
36 }
37 },
38 "%@ runs the command in this app. Type orgstar --help in Terminal.": {
39 "localizations": {
40 "de": {
41 "stringUnit": {
42 "state": "translated",
43 "value": "%@ startet den Befehl in dieser App. Gib im Terminal orgstar --help ein."
44 }
45 },
46 "es": {
47 "stringUnit": {
48 "state": "translated",
49 "value": "%@ ejecuta el comando de esta app. Escribe orgstar --help en Terminal."
50 }
51 },
52 "fr": {
53 "stringUnit": {
54 "state": "translated",
55 "value": "%@ lance la commande de cette app. Tapez orgstar --help dans le Terminal."
56 }
57 },
58 "ja": {
59 "stringUnit": {
60 "state": "translated",
61 "value": "%@ はこのアプリ内のコマンドを実行します。ターミナルで orgstar --help と入力してください。"
62 }
63 },
64 "pt-BR": {
65 "stringUnit": {
66 "state": "translated",
67 "value": "%@ executa o comando deste app. Digite orgstar --help no Terminal."
68 }
69 }
70 }
71 },
4 "%@: git couldn't sign in to the remote (%@). orgstar can't answer prompts; use an SSH key in the agent or a credential helper.": { 72 "%@: git couldn't sign in to the remote (%@). orgstar can't answer prompts; use an SSH key in the agent or a credential helper.": {
5 "localizations": { 73 "localizations": {
6 "de": { 74 "de": {
@@ -239,6 +307,74 @@
239 } 307 }
240 } 308 }
241 }, 309 },
310 "Choose a folder on your PATH for the orgstar command, such as ~/.local/bin or /usr/local/bin.": {
311 "localizations": {
312 "de": {
313 "stringUnit": {
314 "state": "translated",
315 "value": "Wähle einen Ordner in deinem PATH für den Befehl orgstar, etwa ~/.local/bin oder /usr/local/bin."
316 }
317 },
318 "es": {
319 "stringUnit": {
320 "state": "translated",
321 "value": "Elige una carpeta de tu PATH para el comando orgstar, como ~/.local/bin o /usr/local/bin."
322 }
323 },
324 "fr": {
325 "stringUnit": {
326 "state": "translated",
327 "value": "Choisissez un dossier de votre PATH pour la commande orgstar, comme ~/.local/bin ou /usr/local/bin."
328 }
329 },
330 "ja": {
331 "stringUnit": {
332 "state": "translated",
333 "value": "orgstar コマンドを置く PATH 上のフォルダを選んでください(~/.local/bin や /usr/local/bin など)。"
334 }
335 },
336 "pt-BR": {
337 "stringUnit": {
338 "state": "translated",
339 "value": "Escolha uma pasta do seu PATH para o comando orgstar, como ~/.local/bin ou /usr/local/bin."
340 }
341 }
342 }
343 },
344 "Command line": {
345 "localizations": {
346 "de": {
347 "stringUnit": {
348 "state": "translated",
349 "value": "Befehlszeile"
350 }
351 },
352 "es": {
353 "stringUnit": {
354 "state": "translated",
355 "value": "Línea de comandos"
356 }
357 },
358 "fr": {
359 "stringUnit": {
360 "state": "translated",
361 "value": "Ligne de commande"
362 }
363 },
364 "ja": {
365 "stringUnit": {
366 "state": "translated",
367 "value": "コマンドライン"
368 }
369 },
370 "pt-BR": {
371 "stringUnit": {
372 "state": "translated",
373 "value": "Linha de Comando"
374 }
375 }
376 }
377 },
242 "Commit": { 378 "Commit": {
243 "localizations": { 379 "localizations": {
244 "de": { 380 "de": {
@@ -409,6 +545,40 @@
409 } 545 }
410 } 546 }
411 }, 547 },
548 "Couldn't Install orgstar": {
549 "localizations": {
550 "de": {
551 "stringUnit": {
552 "state": "translated",
553 "value": "orgstar konnte nicht installiert werden"
554 }
555 },
556 "es": {
557 "stringUnit": {
558 "state": "translated",
559 "value": "No se ha podido instalar orgstar"
560 }
561 },
562 "fr": {
563 "stringUnit": {
564 "state": "translated",
565 "value": "Impossible d’installer orgstar"
566 }
567 },
568 "ja": {
569 "stringUnit": {
570 "state": "translated",
571 "value": "orgstar をインストールできませんでした"
572 }
573 },
574 "pt-BR": {
575 "stringUnit": {
576 "state": "translated",
577 "value": "Não Foi Possível Instalar o orgstar"
578 }
579 }
580 }
581 },
412 "Couldn't commit in %@: %@": { 582 "Couldn't commit in %@: %@": {
413 "localizations": { 583 "localizations": {
414 "de": { 584 "de": {
@@ -715,6 +885,108 @@
715 } 885 }
716 } 886 }
717 }, 887 },
888 "Install": {
889 "localizations": {
890 "de": {
891 "stringUnit": {
892 "state": "translated",
893 "value": "Installieren"
894 }
895 },
896 "es": {
897 "stringUnit": {
898 "state": "translated",
899 "value": "Instalar"
900 }
901 },
902 "fr": {
903 "stringUnit": {
904 "state": "translated",
905 "value": "Installer"
906 }
907 },
908 "ja": {
909 "stringUnit": {
910 "state": "translated",
911 "value": "インストール"
912 }
913 },
914 "pt-BR": {
915 "stringUnit": {
916 "state": "translated",
917 "value": "Instalar"
918 }
919 }
920 }
921 },
922 "Install Command-Line Tool…": {
923 "localizations": {
924 "de": {
925 "stringUnit": {
926 "state": "translated",
927 "value": "Befehlszeilenwerkzeug installieren …"
928 }
929 },
930 "es": {
931 "stringUnit": {
932 "state": "translated",
933 "value": "Instalar herramienta de línea de comandos…"
934 }
935 },
936 "fr": {
937 "stringUnit": {
938 "state": "translated",
939 "value": "Installer l’outil en ligne de commande…"
940 }
941 },
942 "ja": {
943 "stringUnit": {
944 "state": "translated",
945 "value": "コマンドラインツールをインストール…"
946 }
947 },
948 "pt-BR": {
949 "stringUnit": {
950 "state": "translated",
951 "value": "Instalar Ferramenta de Linha de Comando…"
952 }
953 }
954 }
955 },
956 "Installed orgstar": {
957 "localizations": {
958 "de": {
959 "stringUnit": {
960 "state": "translated",
961 "value": "orgstar installiert"
962 }
963 },
964 "es": {
965 "stringUnit": {
966 "state": "translated",
967 "value": "orgstar instalado"
968 }
969 },
970 "fr": {
971 "stringUnit": {
972 "state": "translated",
973 "value": "orgstar installé"
974 }
975 },
976 "ja": {
977 "stringUnit": {
978 "state": "translated",
979 "value": "orgstar をインストールしました"
980 }
981 },
982 "pt-BR": {
983 "stringUnit": {
984 "state": "translated",
985 "value": "orgstar Instalado"
986 }
987 }
988 }
989 },
718 "License key": { 990 "License key": {
719 "localizations": { 991 "localizations": {
720 "de": { 992 "de": {
@@ -749,6 +1021,40 @@
749 } 1021 }
750 } 1022 }
751 }, 1023 },
1024 "Links the orgstar command into a folder on your PATH, to print the agenda, capture, clock in and out, and export from Terminal.": {
1025 "localizations": {
1026 "de": {
1027 "stringUnit": {
1028 "state": "translated",
1029 "value": "Verlinkt den Befehl orgstar in einen Ordner in deinem PATH, um im Terminal die Agenda auszugeben, zu erfassen, die Uhr zu starten und zu stoppen und zu exportieren."
1030 }
1031 },
1032 "es": {
1033 "stringUnit": {
1034 "state": "translated",
1035 "value": "Enlaza el comando orgstar en una carpeta de tu PATH para mostrar la agenda, capturar, iniciar y detener el reloj y exportar desde Terminal."
1036 }
1037 },
1038 "fr": {
1039 "stringUnit": {
1040 "state": "translated",
1041 "value": "Crée un lien vers la commande orgstar dans un dossier de votre PATH, pour afficher l’agenda, capturer, démarrer et arrêter l’horloge et exporter depuis le Terminal."
1042 }
1043 },
1044 "ja": {
1045 "stringUnit": {
1046 "state": "translated",
1047 "value": "orgstar コマンドへのリンクを PATH 上のフォルダに作成し、ターミナルからアジェンダの表示、キャプチャ、時間計測の開始と終了、書き出しができるようにします。"
1048 }
1049 },
1050 "pt-BR": {
1051 "stringUnit": {
1052 "state": "translated",
1053 "value": "Cria um link para o comando orgstar em uma pasta do seu PATH, para mostrar a agenda, capturar, iniciar e parar o relógio e exportar pelo Terminal."
1054 }
1055 }
1056 }
1057 },
752 "Not a git repository": { 1058 "Not a git repository": {
753 "localizations": { 1059 "localizations": {
754 "de": { 1060 "de": {
@@ -1055,6 +1361,40 @@
1055 } 1361 }
1056 } 1362 }
1057 }, 1363 },
1364 "This copy of orgstar has no command-line tool.": {
1365 "localizations": {
1366 "de": {
1367 "stringUnit": {
1368 "state": "translated",
1369 "value": "Diese Kopie von orgstar enthält kein Befehlszeilenwerkzeug."
1370 }
1371 },
1372 "es": {
1373 "stringUnit": {
1374 "state": "translated",
1375 "value": "Esta copia de orgstar no tiene herramienta de línea de comandos."
1376 }
1377 },
1378 "fr": {
1379 "stringUnit": {
1380 "state": "translated",
1381 "value": "Cette copie d’orgstar n’a pas d’outil en ligne de commande."
1382 }
1383 },
1384 "ja": {
1385 "stringUnit": {
1386 "state": "translated",
1387 "value": "この orgstar にはコマンドラインツールが含まれていません。"
1388 }
1389 },
1390 "pt-BR": {
1391 "stringUnit": {
1392 "state": "translated",
1393 "value": "Esta cópia do orgstar não tem ferramenta de linha de comando."
1394 }
1395 }
1396 }
1397 },
1058 "git isn't installed. Install the Xcode command line tools or git from Homebrew.": { 1398 "git isn't installed. Install the Xcode command line tools or git from Homebrew.": {
1059 "localizations": { 1399 "localizations": {
1060 "de": { 1400 "de": {
@@ -1089,6 +1429,40 @@
1089 } 1429 }
1090 } 1430 }
1091 }, 1431 },
1432 "orgstar can't write in %@: %@. Choose a folder of your own, such as ~/.local/bin, or make the link in Terminal: sudo ln -sf '%@' '%@/orgstar'": {
1433 "localizations": {
1434 "de": {
1435 "stringUnit": {
1436 "state": "translated",
1437 "value": "orgstar kann nicht in %1$@ schreiben: %2$@. Wähle einen eigenen Ordner, etwa ~/.local/bin, oder lege den Link im Terminal an: sudo ln -sf '%3$@' '%4$@/orgstar'"
1438 }
1439 },
1440 "es": {
1441 "stringUnit": {
1442 "state": "translated",
1443 "value": "orgstar no puede escribir en %1$@: %2$@. Elige una carpeta tuya, como ~/.local/bin, o crea el enlace en Terminal: sudo ln -sf '%3$@' '%4$@/orgstar'"
1444 }
1445 },
1446 "fr": {
1447 "stringUnit": {
1448 "state": "translated",
1449 "value": "orgstar ne peut pas écrire dans %1$@ : %2$@. Choisissez un dossier à vous, comme ~/.local/bin, ou créez le lien dans le Terminal : sudo ln -sf '%3$@' '%4$@/orgstar'"
1450 }
1451 },
1452 "ja": {
1453 "stringUnit": {
1454 "state": "translated",
1455 "value": "orgstar は %1$@ に書き込めません: %2$@。~/.local/bin など自分のフォルダを選ぶか、ターミナルでリンクを作成してください: sudo ln -sf '%3$@' '%4$@/orgstar'"
1456 }
1457 },
1458 "pt-BR": {
1459 "stringUnit": {
1460 "state": "translated",
1461 "value": "O orgstar não pode gravar em %1$@: %2$@. Escolha uma pasta sua, como ~/.local/bin, ou crie o link no Terminal: sudo ln -sf '%3$@' '%4$@/orgstar'"
1462 }
1463 }
1464 }
1465 },
1092 "orgstar+ for Mac comes with sponsoring orgstar on GitHub: $60 once, or $5 a month. Editing, the agenda, capture, clocking and search stay free.": { 1466 "orgstar+ for Mac comes with sponsoring orgstar on GitHub: $60 once, or $5 a month. Editing, the agenda, capture, clocking and search stay free.": {
1093 "localizations": { 1467 "localizations": {
1094 "de": { 1468 "de": {
scripts/build-app.sh +10 · view
@@ -31,6 +31,8 @@ swift build -c release $arch_flags --product OrgstarSpotlight
31# shellcheck disable=SC2086 31# shellcheck disable=SC2086
32swift build -c release $arch_flags --product OrgstarWidgets 32swift build -c release $arch_flags --product OrgstarWidgets
33# shellcheck disable=SC2086 33# shellcheck disable=SC2086
34swift build -c release $arch_flags --product OrgstarCLI
35# shellcheck disable=SC2086
34binary="$(swift build -c release $arch_flags --show-bin-path)/Orgstar" 36binary="$(swift build -c release $arch_flags --show-bin-path)/Orgstar"
35 37
36rm -rf "$app" .build/app/dSYMs 38rm -rf "$app" .build/app/dSYMs
@@ -56,6 +58,12 @@ find "$app/Contents/Resources/SwiftMath_SwiftMath.bundle" -path '*/mathFonts.bun
56cp -R "$(dirname "$binary")/Orgstar_OrgMathJax.bundle" "$app/Contents/Resources/" 58cp -R "$(dirname "$binary")/Orgstar_OrgMathJax.bundle" "$app/Contents/Resources/"
57rm -rf "$app/Contents/Resources/Orgstar_OrgMathJax.bundle/Pyodide" 59rm -rf "$app/Contents/Resources/Orgstar_OrgMathJax.bundle/Pyodide"
58 60
61# The orgstar command, which Settings ▸ General links into a folder on the PATH. It reads
62# reveal.js and MathJax from the bundle above.
63mkdir -p "$app/Contents/Helpers"
64cp "$(dirname "$binary")/OrgstarCLI" "$app/Contents/Helpers/orgstar"
65strip -x "$app/Contents/Helpers/orgstar"
66
59# Updates: the appcast and its signing key, for signed builds only; a dev build never checks. 67# Updates: the appcast and its signing key, for signed builds only; a dev build never checks.
60if [ "$sign" != "-" ]; then 68if [ "$sign" != "-" ]; then
61 feed_keys=" <key>SUFeedURL</key> 69 feed_keys=" <key>SUFeedURL</key>
@@ -249,6 +257,8 @@ for item in "$fw/XPCServices/Installer.xpc" "$fw/XPCServices/Downloader.xpc" "$f
249 # shellcheck disable=SC2086 257 # shellcheck disable=SC2086
250 codesign --force --sign "$sign" $sign_flags "$item" 258 codesign --force --sign "$sign" $sign_flags "$item"
251done 259done
260# shellcheck disable=SC2086
261codesign --force --sign "$sign" $sign_flags --identifier sh.krz.orgstar.cli "$app/Contents/Helpers/orgstar"
252 262
253# The hardened runtime needs Calendar access declared for the agenda's events. 263# The hardened runtime needs Calendar access declared for the agenda's events.
254keychain="" 264keychain=""
scripts/sync-strings.sh +1 −1 · view
@@ -29,7 +29,7 @@ done
29 29
30[ -f "$catalog" ] || printf '{\n "sourceLanguage" : "en",\n "strings" : {\n\n },\n "version" : "1.0"\n}\n' > "$catalog" 30[ -f "$catalog" ] || printf '{\n "sourceLanguage" : "en",\n "strings" : {\n\n },\n "version" : "1.0"\n}\n' > "$catalog"
31find "$mac" "$ios" -path '*/arm64/*' -name '*.stringsdata' \ 31find "$mac" "$ios" -path '*/arm64/*' -name '*.stringsdata' \
32 | grep -E '/(Orgstar|OrgstarMobile|OrgstarWidgets|OrgstarShare|OrgstarWatch|OrgstarWatchWidgets)-p\.build/|/(OrgApp|OrgPresentation|OrgEditorAppKit|OrgPrograms)-t?\.build/' \ 32 | grep -E '/(Orgstar|OrgstarMobile|OrgstarWidgets|OrgstarShare|OrgstarWatch|OrgstarWatchWidgets)-p\.build/|/(OrgApp|OrgConfig|OrgPresentation|OrgEditorAppKit|OrgPrograms)-t?\.build/' \
33 > "$mac/stringsdata.txt" 33 > "$mac/stringsdata.txt"
34find "$mas" -path '*/arm64/*' -name '*.stringsdata' | grep -E '/(Orgstar macOS|OrgstarWidgets)\.build/' >> "$mac/stringsdata.txt" 34find "$mas" -path '*/arm64/*' -name '*.stringsdata' | grep -E '/(Orgstar macOS|OrgstarWidgets)\.build/' >> "$mac/stringsdata.txt"
35# The App Store target's folder name has a space, so the list is read a line at a time. 35# The App Store target's folder name has a space, so the list is read a line at a time.
Keyboard shortcuts

Global

⌘K
Command palette & jump
/
Focus search
?
Show this help
g d
Dashboard
g e
Explore repositories
g n
Notifications

Repository & editor

t
Find file in repository
y
Copy immutable SHA permalink
g c
Code tab
g i
Issues tab
g m
Merge requests tab
g b
Builds tab
⌘↵
Submit active form