Sources/OrgCore/Links/Denote.swift

58f3b73e8ff337e5a15111fbb32c0d57cf2346da
orgstar/Sources/OrgCore/Links/Denote.swift history · blame · raw

215 lines · 12063 bytes

22 symbols in this file
  1import Foundation
  2
  3/// Denote's file naming, as `denote-retrieve-filename-identifier` reads it: the identifier
  4/// starts the name (`20261119T120000--title__keywords.org`), or follows `@@` when
  5/// `denote-file-name-components-order` puts it elsewhere.
  6public enum Denote {
  7    /// The identifier in the file name at `path`, or nil when it has none.
  8    public static func identifier(ofFile path: String) -> String? {
  9        let name = (path as NSString).lastPathComponent
 10        if let match = name.firstMatch(of: /^(\d{8}T\d{6})(?:--|__|==|@@|\.|$)/) { return String(match.1) }
 11        if let match = name.firstMatch(of: /@@([^.]+?)(?=--|__|==|@@|\.|$)/) { return String(match.1) }
 12        return nil
 13    }
 14
 15    /// The files under `directories` whose names have an identifier, as Denote lists them.
 16    public static func files(in directories: [String]) -> [String] { DenoteBlocks.files(in: directories).map(\.path) }
 17
 18    /// A query link's regexp, `denote:query-contents:REGEXP` (contents) or
 19    /// `denote:query-filenames:REGEXP`; nil for a link to an identifier.
 20    public static func query(_ path: String) -> (contents: Bool, regexp: String)? {
 21        if path.hasPrefix("query-contents:") { return (true, String(path.dropFirst("query-contents:".count))) }
 22        if path.hasPrefix("query-filenames:") { return (false, String(path.dropFirst("query-filenames:".count))) }
 23        return nil
 24    }
 25
 26    /// A `denote:` link's path split at `::` into the identifier and the search.
 27    public static func split(_ path: String) -> (identifier: String, search: String?) {
 28        guard let range = path.range(of: "::") else { return (path, nil) }
 29        return (String(path[..<range.lowerBound]), String(path[range.upperBound...]))
 30    }
 31
 32    /// The file `denote-get-path-by-id` finds: the one whose name has `identifier`, an Org
 33    /// file before any other.
 34    public static func file(withIdentifier identifier: String, in paths: [String]) -> String? {
 35        let matches = paths.filter { Self.identifier(ofFile: $0) == identifier }
 36        return matches.first { ($0 as NSString).pathExtension == "org" } ?? matches.first
 37    }
 38
 39    // MARK: - Naming new files
 40
 41    /// `denote-excluded-punctuation-regexp`.
 42    static let punctuation = Set("[]{}!@#$%^&*()+'\"?,.|;:~`‘’“”=/")
 43
 44    /// `denote-sluggify-title`: without punctuation, spaces and underscores as one `-`, none
 45    /// at either end, lower case.
 46    public static func slug(_ title: String) -> String {
 47        var out = ""
 48        for character in title.lowercased() where !punctuation.contains(character) {
 49            if character.isWhitespace || character == "_" || character == "-" {
 50                if !out.isEmpty, out.last != "-" { out.append("-") }
 51            } else {
 52                out.append(character)
 53            }
 54        }
 55        while out.last == "-" { out.removeLast() }
 56        return out
 57    }
 58
 59    /// `denote-sluggify-keyword`: one word, lower case, without punctuation or spaces.
 60    public static func keyword(_ word: String) -> String {
 61        String(word.lowercased().filter { !punctuation.contains($0) && !$0.isWhitespace && $0 != "_" && $0 != "-" })
 62    }
 63
 64    /// `denote-sluggify-signature`: like a title, with `=` between words.
 65    public static func signature(_ text: String) -> String {
 66        var out = ""
 67        for character in text.lowercased() where character == "=" || !punctuation.contains(character) && character != "-" {
 68            if character.isWhitespace || character == "_" || character == "=" {
 69                if !out.isEmpty, out.last != "=" { out.append("=") }
 70            } else {
 71                out.append(character)
 72            }
 73        }
 74        while out.last == "=" { out.removeLast() }
 75        return out
 76    }
 77
 78    /// Keywords as `denote-keywords-sort` keeps them: sluggified, without empties or repeats,
 79    /// sorted.
 80    public static func keywords(_ words: [String]) -> [String] {
 81        Array(Set(words.map(keyword).filter { !$0.isEmpty })).sorted()
 82    }
 83
 84    /// `%Y%m%dT%H%M%S` in `calendar`'s time zone.
 85    public static func identifier(for date: Date, calendar: Calendar = .current) -> String {
 86        let c = calendar.dateComponents([.year, .month, .day, .hour, .minute, .second], from: date)
 87        return String(format: "%04d%02d%02dT%02d%02d%02d", c.year!, c.month!, c.day!, c.hour!, c.minute!, c.second!)
 88    }
 89
 90    /// `denote-format-file-name` in the default component order: identifier, signature,
 91    /// title, keywords.
 92    public static func fileName(identifier: String, signature: String? = nil, title: String, keywords: [String], extension ext: String = "org") -> String {
 93        var name = identifier
 94        if let signature, !signature.isEmpty { name += "==" + signature }
 95        let slug = slug(title)
 96        if !slug.isEmpty { name += "--" + slug }
 97        if !keywords.isEmpty { name += "__" + keywords.joined(separator: "_") }
 98        return name + "." + ext
 99    }
100
101    /// `denote-org-front-matter`, dated as an inactive Org timestamp. The signature line is
102    /// left out when there's none.
103    public static func frontMatter(title: String, date: Date, keywords: [String], identifier: String, signature: String = "", calendar: Calendar = .current) -> String {
104        lines(title: title, date: date, keywords: keywords, identifier: identifier, signature: signature, calendar: calendar)
105            .compactMap(\.line).map { $0 + "\n" }.joined() + "\n"
106    }
107
108    /// The front matter's lines by key, in its order; nil for a signature line there isn't,
109    /// and for the date when `date` is nil.
110    static func lines(title: String, date: Date?, keywords: [String], identifier: String, signature: String, calendar: Calendar) -> [(key: String, line: String?)] {
111        let stamp = date.map { date in
112            let c = calendar.dateComponents([.year, .month, .day, .weekday, .hour, .minute], from: date)
113            let day = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"][c.weekday! - 1]
114            return String(format: "[%04d-%02d-%02d %@ %02d:%02d]", c.year!, c.month!, c.day!, day, c.hour!, c.minute!)
115        }
116        let tags = keywords.isEmpty ? "" : ":" + keywords.joined(separator: ":") + ":"
117        return [("title", "#+title:      \(title)"), ("date", stamp.map { "#+date:       \($0)" }), ("filetags", "#+filetags:   \(tags)"),
118                ("identifier", "#+identifier: \(identifier)"), ("signature", signature.isEmpty ? nil : "#+signature:  \(signature)")]
119    }
120
121    /// `denote-rewrite-front-matter`: `text` with its front matter lines set to these values,
122    /// a missing one added after the one before it, an empty signature's removed, other lines
123    /// kept. A nil `date` keeps the date line. Without front matter, `denote-prepend-front-matter`:
124    /// all of it before the text, dated `date` or `now`.
125    public static func rewritingFrontMatter(
126        _ text: String, title: String, keywords: [String], signature: String, date: Date?, identifier: String, now: Date = Date(), calendar: Calendar = .current
127    ) -> String {
128        var lines = text.components(separatedBy: "\n")
129        let wanted = Self.lines(title: title, date: date, keywords: keywords, identifier: identifier, signature: signature, calendar: calendar)
130        func index(_ key: String) -> Int? {
131            lines.prefix(40).firstIndex { $0.trimmingCharacters(in: .whitespaces).lowercased().hasPrefix("#+" + key + ":") }
132        }
133        guard wanted.contains(where: { index($0.key) != nil }) else {
134            return frontMatter(title: title, date: date ?? now, keywords: keywords, identifier: identifier, signature: signature, calendar: calendar) + text
135        }
136        for (position, item) in wanted.enumerated() {
137            if let at = index(item.key) {
138                if let line = item.line { lines[at] = line } else if item.key == "signature" { lines.remove(at: at) }
139            } else if let line = item.line {
140                let before = wanted[..<position].reversed().compactMap { index($0.key) }.first
141                let after = wanted[(position + 1)...].compactMap { index($0.key) }.first
142                lines.insert(line, at: before.map { $0 + 1 } ?? after ?? 0)
143            }
144        }
145        return lines.joined(separator: "\n")
146    }
147
148    // MARK: - Reading names and front matter
149
150    /// The parts of a Denote file name, in any component order.
151    public struct Name: Sendable, Equatable {
152        public var identifier: String?
153        public var signature: String?
154        public var title: String?
155        public var keywords: [String]
156        public var ext: String
157    }
158
159    public static func name(ofFile path: String) -> Name {
160        let file = (path as NSString).lastPathComponent
161        let ext = (file as NSString).pathExtension
162        let stem = ext.isEmpty ? file : String(file.dropLast(ext.count + 1))
163        var name = Name(identifier: identifier(ofFile: file), keywords: [], ext: ext)
164        for match in stem.matches(of: /(--|__|==)(.+?)(?=--|__|==|@@|$)/) {
165            let value = String(match.2)
166            switch match.1 {
167            case "--": name.title = value
168            case "__": name.keywords = value.split(separator: "_").map(String.init)
169            default: name.signature = value
170            }
171        }
172        return name
173    }
174
175    /// The `#+title`, `#+filetags`, `#+identifier` and `#+signature` of a file's front matter.
176    public static func frontMatter(of text: String) -> (title: String?, keywords: [String]?, identifier: String?, signature: String?) {
177        func value(_ key: String) -> String? {
178            for line in text.split(separator: "\n", omittingEmptySubsequences: false).prefix(40) {
179                let trimmed = line.trimmingCharacters(in: .whitespaces)
180                guard trimmed.lowercased().hasPrefix("#+" + key + ":") else { continue }
181                return trimmed.dropFirst(key.count + 3).trimmingCharacters(in: .whitespaces)
182            }
183            return nil
184        }
185        let keywords = value("filetags").map { $0.split(separator: ":").map(String.init).filter { !$0.isEmpty } }
186        return (value("title"), keywords, value("identifier")?.nonEmptyOrNil, value("signature"))
187    }
188
189    /// The front matter's `#+date:`, an Org timestamp, in `calendar`'s time zone.
190    public static func date(of text: String, calendar: Calendar = .current) -> Date? {
191        guard let match = text.firstMatch(of: /(?im)^[ \t]*#\+date:[ \t]*[\[<](\d{4})-(\d{2})-(\d{2})(?:[^\]>\d]*(\d{1,2}):(\d{2}))?/) else { return nil }
192        return calendar.date(from: DateComponents(year: Int(match.1), month: Int(match.2), day: Int(match.3),
193                                                  hour: match.4.flatMap { Int($0) } ?? 0, minute: match.5.flatMap { Int($0) } ?? 0))
194    }
195
196    /// `denote-rename-file-using-front-matter`: the name the file at `path` takes from its
197    /// front matter's title, keywords and signature, each empty when its line is missing. Nil
198    /// when the file has no front matter, or no identifier in it or its name.
199    public static func renamed(_ path: String, text: String) -> String? {
200        let current = name(ofFile: path)
201        let front = frontMatter(of: text)
202        guard front.title != nil || front.keywords != nil || front.identifier != nil || front.signature != nil,
203              let identifier = front.identifier ?? current.identifier else { return nil }
204        // In the front matter's order: Denote sorts keywords only as it prompts for them.
205        var seen = Set<String>()
206        let keywords = (front.keywords ?? []).map(keyword).filter { !$0.isEmpty && seen.insert($0).inserted }
207        let file = fileName(identifier: identifier, signature: front.signature.map(signature), title: front.title ?? "", keywords: keywords,
208                            extension: current.ext.isEmpty ? "org" : current.ext)
209        return ((path as NSString).deletingLastPathComponent as NSString).appendingPathComponent(file)
210    }
211}
212
213private extension String {
214    var nonEmptyOrNil: String? { isEmpty ? nil : self }
215}