Sources/OrgCore/Links/Denote.swift

c396b3453f7cf76ac49e5e2707e01bf5c5753508
orgstar/Sources/OrgCore/Links/Denote.swift

150 lines · 7394 bytes

  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    /// A `denote:` link's path split at `::` into the identifier and the search.
 16    public static func split(_ path: String) -> (identifier: String, search: String?) {
 17        guard let range = path.range(of: "::") else { return (path, nil) }
 18        return (String(path[..<range.lowerBound]), String(path[range.upperBound...]))
 19    }
 20
 21    /// The file `denote-get-path-by-id` finds: the one whose name has `identifier`, an Org
 22    /// file before any other.
 23    public static func file(withIdentifier identifier: String, in paths: [String]) -> String? {
 24        let matches = paths.filter { Self.identifier(ofFile: $0) == identifier }
 25        return matches.first { ($0 as NSString).pathExtension == "org" } ?? matches.first
 26    }
 27
 28    // MARK: - Naming new files
 29
 30    /// `denote-excluded-punctuation-regexp`.
 31    static let punctuation = Set("[]{}!@#$%^&*()+'\"?,.|;:~`‘’“”=<>/")
 32
 33    /// `denote-sluggify-title`: without punctuation, spaces and underscores as one `-`, none
 34    /// at either end, lower case.
 35    public static func slug(_ title: String) -> String {
 36        var out = ""
 37        for character in title.lowercased() where !punctuation.contains(character) {
 38            if character.isWhitespace || character == "_" || character == "-" {
 39                if !out.isEmpty, out.last != "-" { out.append("-") }
 40            } else {
 41                out.append(character)
 42            }
 43        }
 44        while out.last == "-" { out.removeLast() }
 45        return out
 46    }
 47
 48    /// `denote-sluggify-keyword`: one word, lower case, without punctuation or spaces.
 49    public static func keyword(_ word: String) -> String {
 50        String(word.lowercased().filter { !punctuation.contains($0) && !$0.isWhitespace && $0 != "_" && $0 != "-" })
 51    }
 52
 53    /// Keywords as `denote-keywords-sort` keeps them: sluggified, without empties or repeats,
 54    /// sorted.
 55    public static func keywords(_ words: [String]) -> [String] {
 56        Array(Set(words.map(keyword).filter { !$0.isEmpty })).sorted()
 57    }
 58
 59    /// `%Y%m%dT%H%M%S` in `calendar`'s time zone.
 60    public static func identifier(for date: Date, calendar: Calendar = .current) -> String {
 61        let c = calendar.dateComponents([.year, .month, .day, .hour, .minute, .second], from: date)
 62        return String(format: "%04d%02d%02dT%02d%02d%02d", c.year!, c.month!, c.day!, c.hour!, c.minute!, c.second!)
 63    }
 64
 65    /// `denote-format-file-name` in the default component order: identifier, signature,
 66    /// title, keywords.
 67    public static func fileName(identifier: String, signature: String? = nil, title: String, keywords: [String], extension ext: String = "org") -> String {
 68        var name = identifier
 69        if let signature, !signature.isEmpty { name += "==" + signature }
 70        let slug = slug(title)
 71        if !slug.isEmpty { name += "--" + slug }
 72        if !keywords.isEmpty { name += "__" + keywords.joined(separator: "_") }
 73        return name + "." + ext
 74    }
 75
 76    /// `denote-org-front-matter`, dated as an inactive Org timestamp.
 77    public static func frontMatter(title: String, date: Date, keywords: [String], identifier: String, calendar: Calendar = .current) -> String {
 78        let c = calendar.dateComponents([.year, .month, .day, .weekday, .hour, .minute], from: date)
 79        let day = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"][c.weekday! - 1]
 80        let stamp = String(format: "[%04d-%02d-%02d %@ %02d:%02d]", c.year!, c.month!, c.day!, day, c.hour!, c.minute!)
 81        let tags = keywords.isEmpty ? "" : ":" + keywords.joined(separator: ":") + ":"
 82        return """
 83            #+title:      \(title)
 84            #+date:       \(stamp)
 85            #+filetags:   \(tags)
 86            #+identifier: \(identifier)
 87
 88
 89            """
 90    }
 91
 92    // MARK: - Reading names and front matter
 93
 94    /// The parts of a Denote file name, in any component order.
 95    public struct Name: Sendable, Equatable {
 96        public var identifier: String?
 97        public var signature: String?
 98        public var title: String?
 99        public var keywords: [String]
100        public var ext: String
101    }
102
103    public static func name(ofFile path: String) -> Name {
104        let file = (path as NSString).lastPathComponent
105        let ext = (file as NSString).pathExtension
106        let stem = ext.isEmpty ? file : String(file.dropLast(ext.count + 1))
107        var name = Name(identifier: identifier(ofFile: file), keywords: [], ext: ext)
108        for match in stem.matches(of: /(--|__|==)(.+?)(?=--|__|==|@@|$)/) {
109            let value = String(match.2)
110            switch match.1 {
111            case "--": name.title = value
112            case "__": name.keywords = value.split(separator: "_").map(String.init)
113            default: name.signature = value
114            }
115        }
116        return name
117    }
118
119    /// The `#+title`, `#+filetags` and `#+identifier` of a file's front matter.
120    public static func frontMatter(of text: String) -> (title: String?, keywords: [String]?, identifier: String?) {
121        func value(_ key: String) -> String? {
122            for line in text.split(separator: "\n", omittingEmptySubsequences: false).prefix(40) {
123                let trimmed = line.trimmingCharacters(in: .whitespaces)
124                guard trimmed.lowercased().hasPrefix("#+" + key + ":") else { continue }
125                return trimmed.dropFirst(key.count + 3).trimmingCharacters(in: .whitespaces)
126            }
127            return nil
128        }
129        let keywords = value("filetags").map { $0.split(separator: ":").map(String.init).filter { !$0.isEmpty } }
130        return (value("title"), keywords, value("identifier")?.nonEmptyOrNil)
131    }
132
133    /// `denote-rename-file-using-front-matter`: the name the file at `path` takes from its
134    /// front matter, keeping the identifier and signature. Nil when the file has no identifier
135    /// in its name or front matter.
136    public static func renamed(_ path: String, text: String) -> String? {
137        let current = name(ofFile: path)
138        let front = frontMatter(of: text)
139        guard let identifier = current.identifier ?? front.identifier else { return nil }
140        let title = front.title ?? current.title.map { $0.replacingOccurrences(of: "-", with: " ") } ?? ""
141        let keywords = keywords(front.keywords ?? current.keywords)
142        let file = fileName(identifier: identifier, signature: current.signature, title: title, keywords: keywords,
143                            extension: current.ext.isEmpty ? "org" : current.ext)
144        return ((path as NSString).deletingLastPathComponent as NSString).appendingPathComponent(file)
145    }
146}
147
148private extension String {
149    var nonEmptyOrNil: String? { isEmpty ? nil : self }
150}
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