Sources/OrgApp/Dailies.swift

c396b3453f7cf76ac49e5e2707e01bf5c5753508
orgstar/Sources/OrgApp/Dailies.swift

128 lines · 7082 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
 31        public init(keyword: String = "journal", title: String = "%A %e %B %Y") {
 32            self.keyword = keyword
 33            self.title = title
 34        }
 35    }
 36
 37    public init(directory: String, file: String = "%<%Y-%m-%d>.org", head: String = "#+title: %<%Y-%m-%d>\n", entry: String = "* %?", journal: Journal? = nil) {
 38        self.directory = directory
 39        self.file = file
 40        self.head = head
 41        self.entry = entry
 42        self.journal = journal
 43    }
 44
 45    /// The settings' dailies: `org-roam-directory`, by default the first folder, and
 46    /// `org-roam-dailies-directory` in it. Nil without a folder.
 47    public static func configured(roots: [String], defaults: UserDefaults = .standard) -> Dailies? {
 48        if OrgPreferences.usesDenote(defaults) {
 49            guard let base = DenoteNote.directory(roots: roots, defaults: defaults) else { return nil }
 50            return Dailies(directory: OrgAttach.expand(OrgPreferences.denoteJournalDirectory(defaults), in: base), entry: OrgPreferences.dailiesEntry(defaults),
 51                           journal: Journal(keyword: Denote.keyword(OrgPreferences.denoteJournalKeyword(defaults)), title: OrgPreferences.denoteJournalTitle(defaults)))
 52        }
 53        let roam = OrgPreferences.roamDirectory(defaults)
 54        guard let base = roam.isEmpty ? roots.first : OrgAttach.expand(roam, in: roots.first ?? NSHomeDirectory()) else { return nil }
 55        return Dailies(directory: OrgAttach.expand(OrgPreferences.dailiesDirectory(defaults), in: base),
 56                       file: OrgPreferences.dailiesFile(defaults), head: OrgPreferences.dailiesHead(defaults), entry: OrgPreferences.dailiesEntry(defaults))
 57    }
 58
 59    /// `format-time-string` for each `%<format>`, in the local time zone.
 60    public static func expandTime(_ template: String, _ day: Date) -> String {
 61        template.replacing(/%<([^>]*)>/) { strftime(String($0.1), day) }
 62    }
 63
 64    static func strftime(_ format: String, _ date: Date) -> String {
 65        var time = time_t(date.timeIntervalSince1970)
 66        var parts = tm()
 67        localtime_r(&time, &parts)
 68        var buffer = [CChar](repeating: 0, count: 256)
 69        let count = Darwin.strftime(&buffer, buffer.count, format, &parts)
 70        return String(decoding: buffer[..<count].map { UInt8(bitPattern: $0) }, as: UTF8.self)
 71    }
 72
 73    public func path(for day: Date) -> String {
 74        if let journal {
 75            let date = Denote.identifier(for: day).prefix(8)
 76            if let found = files().first(where: { Denote.identifier(ofFile: $0)?.hasPrefix(date) == true }) { return found }
 77            let name = Denote.fileName(identifier: Denote.identifier(for: day), title: Self.strftime(journal.title, day), keywords: [journal.keyword])
 78            return (directory as NSString).appendingPathComponent(name)
 79        }
 80        return OrgAttach.expand(Self.expandTime(file, day).trimmingCharacters(in: .whitespaces), in: directory)
 81    }
 82
 83    /// The file's text when it's new: the head, ending in a newline, under a property drawer
 84    /// with the ID, as `org-entry-put` puts it at the start.
 85    public func newText(_ day: Date, id: String) -> String {
 86        if let journal {
 87            return Denote.frontMatter(title: Self.strftime(journal.title, day), date: day, keywords: [journal.keyword], identifier: Denote.identifier(for: day))
 88        }
 89        var text = Self.expandTime(head, day)
 90        if !text.hasSuffix("\n") { text += "\n" }
 91        return OrgAttach.ensuringID(text, at: 0) { id }.text
 92    }
 93
 94    /// The daily file for `day`, made when missing. True when it's new.
 95    @discardableResult
 96    public func ensure(_ day: Date, id: () -> String = { UUID().uuidString.lowercased() }) throws -> (path: String, created: Bool) {
 97        let path = path(for: day)
 98        guard !FileManager.default.fileExists(atPath: path) else { return (path, false) }
 99        try FileManager.default.createDirectory(atPath: (path as NSString).deletingLastPathComponent, withIntermediateDirectories: true)
100        try newText(day, id: id()).write(toFile: path, atomically: true, encoding: .utf8)
101        return (path, true)
102    }
103
104    /// `org-roam-dailies--list-files`: the org files in the folder and below, without hidden,
105    /// backup and auto-save files, sorted. For a Denote journal, those with its keyword.
106    public func files() -> [String] {
107        let paths = (FileManager.default.enumerator(atPath: directory)?.allObjects as? [String]) ?? []
108        return paths.compactMap { relative -> String? in
109            let name = (relative as NSString).lastPathComponent
110            guard (relative as NSString).pathExtension == "org", !relative.split(separator: "/").contains(where: { $0.hasPrefix(".") }),
111                  !name.hasPrefix("#"), !name.hasSuffix("~") else { return nil }
112            if let journal, !Denote.name(ofFile: name).keywords.contains(journal.keyword) { return nil }
113            return (directory as NSString).appendingPathComponent(relative)
114        }.sorted()
115    }
116
117    /// `org-roam-dailies-goto-next-note` from the daily file at `path`, `n` notes on
118    /// (back for negative `n`).
119    public func neighbor(of path: String, by n: Int) throws -> String {
120        func real(_ p: String) -> String { URL(fileURLWithPath: p).resolvingSymlinksInPath().path }
121        guard real(path).hasPrefix(real(directory) + "/") else { throw Failure("Not in a daily-note") }
122        let all = files()
123        guard let position = all.map(real).firstIndex(of: real(path)) else { throw Failure("Can't find current note file - have you saved it yet?") }
124        if n >= 0, position == all.count - 1 { throw Failure("Already at newest note") }
125        if n < 0, position == 0 { throw Failure("Already at oldest note") }
126        return all[min(max(position + n, 0), all.count - 1)]
127    }
128}
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