Sources/OrgApp/Dailies.swift
149 lines · 8322 bytes
1import Foundation
2import OrgCore
3
4/// org-roam-dailies (org-roam 2.3): a file a day in `org-roam-dailies-directory` under
5/// `org-roam-directory`, named and started as its default capture template does,
6/// `%<%Y-%m-%d>.org` with `#+title: %<%Y-%m-%d>`, and an ID like any new org-roam file.
7/// With `journal` set, denote-journal's instead: a Denote note a day with the journal keyword.
8public struct Dailies: Sendable, Equatable {
9 public struct Failure: Error, Equatable, CustomStringConvertible {
10 public let description: String
11 public init(_ description: String) { self.description = description }
12 }
13
14 /// The folder the daily files are in.
15 public var directory: String
16 /// The file name, with `%<…>` for the date.
17 public var file: String
18 /// What a new file starts with.
19 public var head: String
20 /// What Capture to Daily adds, an org-capture template.
21 public var entry: String
22 /// denote-journal's settings, in place of `file` and `head`.
23 public var journal: Journal?
24
25 public struct Journal: Sendable, Equatable {
26 /// `denote-journal-keyword`.
27 public var keyword: String
28 /// `denote-journal-title-format`, a `format-time-string` format.
29 public var title: String
30 /// `denote-journal-interval`: `daily`, `weekly`, `monthly` or `yearly`, how long one
31 /// entry lasts.
32 public var interval: String
33
34 public init(keyword: String = "journal", title: String = "%A %-e %B %Y %H:%M", interval: String = "daily") {
35 self.keyword = keyword
36 self.title = title
37 self.interval = interval
38 }
39
40 /// `denote-journal--filename-regexp`: whether an identifier's date is in `day`'s
41 /// interval, weeks starting on Monday.
42 func covers(_ identifier: String, _ day: Date) -> Bool {
43 let date = Denote.identifier(for: day)
44 switch interval {
45 case "monthly": return identifier.hasPrefix(date.prefix(6))
46 case "yearly": return identifier.hasPrefix(date.prefix(4))
47 case "weekly":
48 var calendar = Calendar(identifier: .gregorian)
49 calendar.firstWeekday = 2
50 calendar.timeZone = .current
51 guard let week = calendar.dateInterval(of: .weekOfYear, for: day) else { return false }
52 return (0..<7).contains { identifier.hasPrefix(Denote.identifier(for: week.start.addingTimeInterval(Double($0) * 86400 + 43200)).prefix(8)) }
53 default: return identifier.hasPrefix(date.prefix(8))
54 }
55 }
56 }
57
58 public init(directory: String, file: String = "%<%Y-%m-%d>.org", head: String = "#+title: %<%Y-%m-%d>\n", entry: String = "* %?", journal: Journal? = nil) {
59 self.directory = directory
60 self.file = file
61 self.head = head
62 self.entry = entry
63 self.journal = journal
64 }
65
66 /// The settings' dailies: `org-roam-directory`, by default the first folder, and
67 /// `org-roam-dailies-directory` in it. Nil without a folder.
68 public static func configured(roots: [String], defaults: UserDefaults = .standard) -> Dailies? {
69 if OrgPreferences.usesDenote(defaults) {
70 guard let base = DenoteNote.directory(roots: roots, defaults: defaults) else { return nil }
71 return Dailies(directory: OrgAttach.expand(OrgPreferences.denoteJournalDirectory(defaults), in: base), entry: OrgPreferences.dailiesEntry(defaults),
72 journal: Journal(keyword: Denote.keyword(OrgPreferences.denoteJournalKeyword(defaults)), title: OrgPreferences.denoteJournalTitle(defaults),
73 interval: OrgPreferences.denoteJournalInterval(defaults)))
74 }
75 let roam = OrgPreferences.roamDirectory(defaults)
76 guard let base = roam.isEmpty ? roots.first : OrgAttach.expand(roam, in: roots.first ?? NSHomeDirectory()) else { return nil }
77 return Dailies(directory: OrgAttach.expand(OrgPreferences.dailiesDirectory(defaults), in: base),
78 file: OrgPreferences.dailiesFile(defaults), head: OrgPreferences.dailiesHead(defaults), entry: OrgPreferences.dailiesEntry(defaults))
79 }
80
81 /// `format-time-string` for each `%<format>`, in the local time zone.
82 public static func expandTime(_ template: String, _ day: Date) -> String {
83 template.replacing(/%<([^>]*)>/) { strftime(String($0.1), day) }
84 }
85
86 static func strftime(_ format: String, _ date: Date) -> String {
87 var time = time_t(date.timeIntervalSince1970)
88 var parts = tm()
89 localtime_r(&time, &parts)
90 var buffer = [CChar](repeating: 0, count: 256)
91 let count = Darwin.strftime(&buffer, buffer.count, format, &parts)
92 return String(decoding: buffer[..<count].map { UInt8(bitPattern: $0) }, as: UTF8.self)
93 }
94
95 public func path(for day: Date) -> String {
96 if let journal {
97 if let found = files().first(where: { Denote.identifier(ofFile: $0).map { journal.covers($0, day) } == true }) { return found }
98 let name = Denote.fileName(identifier: Denote.identifier(for: day), title: Self.strftime(journal.title, day), keywords: [journal.keyword])
99 return (directory as NSString).appendingPathComponent(name)
100 }
101 return OrgAttach.expand(Self.expandTime(file, day).trimmingCharacters(in: .whitespaces), in: directory)
102 }
103
104 /// The file's text when it's new: the head, ending in a newline, under a property drawer
105 /// with the ID, as `org-entry-put` puts it at the start.
106 public func newText(_ day: Date, id: String) -> String {
107 if let journal {
108 return Denote.frontMatter(title: Self.strftime(journal.title, day), date: day, keywords: [journal.keyword], identifier: Denote.identifier(for: day))
109 }
110 var text = Self.expandTime(head, day)
111 if !text.hasSuffix("\n") { text += "\n" }
112 return OrgAttach.ensuringID(text, at: 0) { id }.text
113 }
114
115 /// The daily file for `day`, made when missing. True when it's new.
116 @discardableResult
117 public func ensure(_ day: Date, id: () -> String = { UUID().uuidString.lowercased() }) throws -> (path: String, created: Bool) {
118 let path = path(for: day)
119 guard !FileManager.default.fileExists(atPath: path) else { return (path, false) }
120 try FileManager.default.createDirectory(atPath: (path as NSString).deletingLastPathComponent, withIntermediateDirectories: true)
121 try newText(day, id: id()).write(toFile: path, atomically: true, encoding: .utf8)
122 return (path, true)
123 }
124
125 /// `org-roam-dailies--list-files`: the org files in the folder and below, without hidden,
126 /// backup and auto-save files, sorted. For a Denote journal, those with its keyword.
127 public func files() -> [String] {
128 let paths = (FileManager.default.enumerator(atPath: directory)?.allObjects as? [String]) ?? []
129 return paths.compactMap { relative -> String? in
130 let name = (relative as NSString).lastPathComponent
131 guard (relative as NSString).pathExtension == "org", !relative.split(separator: "/").contains(where: { $0.hasPrefix(".") }),
132 !name.hasPrefix("#"), !name.hasSuffix("~") else { return nil }
133 if let journal, !Denote.name(ofFile: name).keywords.contains(journal.keyword) { return nil }
134 return (directory as NSString).appendingPathComponent(relative)
135 }.sorted()
136 }
137
138 /// `org-roam-dailies-goto-next-note` from the daily file at `path`, `n` notes on
139 /// (back for negative `n`).
140 public func neighbor(of path: String, by n: Int) throws -> String {
141 func real(_ p: String) -> String { URL(fileURLWithPath: p).resolvingSymlinksInPath().path }
142 guard real(path).hasPrefix(real(directory) + "/") else { throw Failure("Not in a daily-note") }
143 let all = files()
144 guard let position = all.map(real).firstIndex(of: real(path)) else { throw Failure("Can't find current note file - have you saved it yet?") }
145 if n >= 0, position == all.count - 1 { throw Failure("Already at newest note") }
146 if n < 0, position == 0 { throw Failure("Already at oldest note") }
147 return all[min(max(position + n, 0), all.count - 1)]
148 }
149}