Sources/OrgCore/Links/Denote.swift

9f4554a96f2c77e714e6b67f2669774ffc3c57df
orgstar/Sources/OrgCore/Links/Denote.swift

396 lines · 22105 bytes

34 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    // MARK: - File types
102
103    /// `denote-file-types`: the formats Denote writes notes in.
104    public enum FileType: String, Sendable, CaseIterable {
105        case org
106        /// Markdown with YAML front matter between `---` lines.
107        case markdownYAML = "markdown-yaml"
108        /// Markdown with TOML front matter between `+++` lines.
109        case markdownTOML = "markdown-toml"
110        /// Plain text, the front matter ended by a line of dashes.
111        case text
112
113        /// The extension, without the dot.
114        public var ext: String {
115            switch self {
116            case .org: "org"
117            case .markdownYAML, .markdownTOML: "md"
118            case .text: "txt"
119            }
120        }
121
122        public var isMarkdown: Bool { self == .markdownYAML || self == .markdownTOML }
123
124        /// `denote-file-type` of a file: by its extension, `.md` by whether `text` starts with
125        /// `---` or `+++`, else `preferred` when that is a Markdown type, else YAML. Nil for a
126        /// file Denote has no type for.
127        public init?(path: String, text: String? = nil, preferred: FileType = .org) {
128            switch (path as NSString).pathExtension {
129            case "org": self = .org
130            case "txt": self = .text
131            case "md":
132                if text?.hasPrefix("---") == true { self = .markdownYAML }
133                else if text?.hasPrefix("+++") == true { self = .markdownTOML }
134                else { self = preferred.isMarkdown ? preferred : .markdownYAML }
135            default: return nil
136            }
137        }
138    }
139
140    /// A front matter line, in the template's order.
141    enum Component: CaseIterable { case title, date, keywords, identifier, signature }
142
143    /// The key a component's line starts with, as `denote-file-types`'s key regexps match it.
144    static func key(_ component: Component, _ type: FileType) -> String {
145        let name = switch component {
146        case .title: "title"
147        case .date: "date"
148        case .keywords: type == .org ? "filetags" : "tags"
149        case .identifier: "identifier"
150        case .signature: "signature"
151        }
152        return type == .org ? "#+" + name : name
153    }
154
155    /// The key as the template writes it, separator and padding included.
156    static func written(_ component: Component, _ type: FileType) -> String {
157        let key = key(component, type)
158        let padding = String(repeating: " ", count: max(0, (type == .org ? 12 : 10) - key.count))
159        return type == .markdownTOML ? key + padding + " = " : key + ":" + padding + " "
160    }
161
162    /// Where the value starts on `line` when it is `component`'s line: after the key, the
163    /// spaces before the separator, the separator and the spaces after it. Keys match without
164    /// case; an Org key may be indented.
165    static func valueStart(_ line: Substring, _ component: Component, _ type: FileType) -> String.Index? {
166        var rest = type == .org ? line.drop { $0 == " " || $0 == "\t" } : line
167        let key = key(component, type)
168        guard rest.prefix(key.count).lowercased() == key else { return nil }
169        rest = rest.dropFirst(key.count).drop { $0 == " " || $0 == "\t" }
170        guard rest.first == (type == .markdownTOML ? "=" : ":") else { return nil }
171        return rest.dropFirst().drop { $0 == " " || $0 == "\t" }.startIndex
172    }
173
174    /// `%S` of a string: quoted, with `"` and `\` escaped.
175    static func quoted(_ s: String) -> String {
176        "\"" + s.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\"") + "\""
177    }
178
179    /// A date as the type's `:date-value-function` writes it: an inactive Org timestamp,
180    /// RFC 3339 for Markdown, ISO 8601 for text.
181    static func stamp(_ date: Date, _ type: FileType, calendar: Calendar) -> String {
182        let c = calendar.dateComponents([.year, .month, .day, .weekday, .hour, .minute, .second], from: date)
183        let day = String(format: "%04d-%02d-%02d", c.year!, c.month!, c.day!)
184        switch type {
185        case .org:
186            return String(format: "[%@ %@ %02d:%02d]", day, ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"][c.weekday! - 1], c.hour!, c.minute!)
187        case .markdownYAML, .markdownTOML:
188            let offset = calendar.timeZone.secondsFromGMT(for: date) / 60
189            return String(format: "%@T%02d:%02d:%02d%@%02d:%02d", day, c.hour!, c.minute!, c.second!, offset < 0 ? "-" : "+", abs(offset) / 60, abs(offset) % 60)
190        case .text:
191            return day
192        }
193    }
194
195    /// Each component's value as the type writes it; nil for the date when `date` is nil.
196    static func values(title: String, date: Date?, keywords: [String], identifier: String, signature: String, type: FileType, calendar: Calendar) -> [Component: String] {
197        let md = type.isMarkdown
198        let tags = switch type {
199        case .org: keywords.isEmpty ? "" : ":" + keywords.joined(separator: ":") + ":"
200        case .markdownYAML, .markdownTOML: "[" + keywords.map(quoted).joined(separator: ", ") + "]"
201        case .text: keywords.joined(separator: "  ")
202        }
203        var values: [Component: String] = [.title: md ? quoted(title) : title, .keywords: tags, .identifier: md ? quoted(identifier) : identifier,
204                                           .signature: md ? quoted(signature) : signature]
205        values[.date] = date.map { stamp($0, type, calendar: calendar) }
206        return values
207    }
208
209    /// The front matter of a new note, as `denote--format-front-matter` writes the type's
210    /// template (`denote-org-front-matter` and the others): every line, except the signature's
211    /// when there is none, then a blank line.
212    public static func frontMatter(
213        title: String, date: Date, keywords: [String], identifier: String, signature: String = "", type: FileType = .org, calendar: Calendar = .current
214    ) -> String {
215        let values = values(title: title, date: date, keywords: keywords, identifier: identifier, signature: signature, type: type, calendar: calendar)
216        let lines = Component.allCases.filter { $0 != .signature || !signature.isEmpty }.map { written($0, type) + values[$0]! }
217        let (open, close): ([String], [String]) = switch type {
218        case .org: ([], [])
219        case .markdownYAML: (["---"], ["---"])
220        case .markdownTOML: (["+++"], ["+++"])
221        case .text: ([], ["---------------------------"])
222        }
223        return (open + lines + close).map { $0 + "\n" }.joined() + "\n"
224    }
225
226    /// `denote-rewrite-front-matter`: `text` with its front matter set to these values. A line
227    /// that is there keeps its key and spacing and gets the new value; an empty signature's
228    /// line goes; a missing line with a value is added after the line before it in the
229    /// template, else before the one after it. A nil `date` keeps the date line. Without front
230    /// matter, `denote-prepend-front-matter`: all of it before the text, dated `date` or `now`.
231    public static func rewritingFrontMatter(
232        _ text: String, title: String, keywords: [String], signature: String, date: Date?, identifier: String, now: Date = Date(),
233        type: FileType = .org, calendar: Calendar = .current
234    ) -> String {
235        var lines = text.components(separatedBy: "\n")
236        let values = values(title: title, date: date, keywords: keywords, identifier: identifier, signature: signature, type: type, calendar: calendar)
237        func index(_ component: Component) -> Int? {
238            lines.prefix(40).firstIndex { valueStart($0[...], component, type) != nil }
239        }
240        guard Component.allCases.contains(where: { index($0) != nil }) else {
241            return frontMatter(title: title, date: date ?? now, keywords: keywords, identifier: identifier, signature: signature, type: type, calendar: calendar) + text
242        }
243        let all = Component.allCases
244        for (position, component) in all.enumerated() {
245            let hasValue = switch component {
246            case .title: !title.isEmpty
247            case .date: date != nil
248            case .keywords: !keywords.isEmpty
249            case .identifier: !identifier.isEmpty
250            case .signature: !signature.isEmpty
251            }
252            if let at = index(component) {
253                if component == .signature, !hasValue {
254                    lines.remove(at: at)
255                } else if let value = values[component], let start = valueStart(lines[at][...], component, type) {
256                    lines[at] = String(lines[at][..<start]) + value
257                }
258            } else if hasValue, let value = values[component] {
259                let before = all[..<position].reversed().compactMap { index($0) }.first
260                let after = all[(position + 1)...].compactMap { index($0) }.first
261                lines.insert(written(component, type) + value, at: before.map { $0 + 1 } ?? after ?? 0)
262            }
263        }
264        return lines.joined(separator: "\n")
265    }
266
267    // MARK: - Reading names and front matter
268
269    /// The parts of a Denote file name, in any component order.
270    public struct Name: Sendable, Equatable {
271        public var identifier: String?
272        public var signature: String?
273        public var title: String?
274        public var keywords: [String]
275        public var ext: String
276    }
277
278    public static func name(ofFile path: String) -> Name {
279        let file = (path as NSString).lastPathComponent
280        let ext = (file as NSString).pathExtension
281        let stem = ext.isEmpty ? file : String(file.dropLast(ext.count + 1))
282        var name = Name(identifier: identifier(ofFile: file), keywords: [], ext: ext)
283        for match in stem.matches(of: /(--|__|==)(.+?)(?=--|__|==|@@|$)/) {
284            let value = String(match.2)
285            switch match.1 {
286            case "--": name.title = value
287            case "__": name.keywords = value.split(separator: "_").map(String.init)
288            default: name.signature = value
289            }
290        }
291        return name
292    }
293
294
295    /// A component's value on its first line among the first 40, untrimmed.
296    static func rawValue(_ component: Component, in text: String, type: FileType) -> Substring? {
297        for line in text.split(separator: "\n", omittingEmptySubsequences: false).prefix(40) {
298            if let start = valueStart(line, component, type) { return line[start...] }
299        }
300        return nil
301    }
302
303    /// The title, keywords, identifier and signature of a file's front matter, read as the
304    /// type's `:…-value-reverse-function`s read them: Markdown values without the whitespace
305    /// and quotes around them, keywords split at colons, commas and spaces.
306    public static func frontMatter(of text: String, type: FileType = .org) -> (title: String?, keywords: [String]?, identifier: String?, signature: String?) {
307        func value(_ component: Component) -> String? {
308            guard let raw = rawValue(component, in: text, type: type) else { return nil }
309            let trimmed = raw.trimmingCharacters(in: .whitespaces)
310            return type.isMarkdown ? trimmed.trimmingCharacters(in: CharacterSet(charactersIn: "\"'")) : trimmed
311        }
312        let keywords = rawValue(.keywords, in: text, type: type).map { raw in
313            type == .org ? raw.split(separator: ":").map { $0.trimmingCharacters(in: .whitespaces) }.filter { !$0.isEmpty }
314                : raw.split { $0 == ":" || $0 == "," || $0.isWhitespace }.map { $0.trimmingCharacters(in: CharacterSet(charactersIn: "[] \"'")) }.filter { !$0.isEmpty }
315        }
316        return (value(.title), keywords, value(.identifier)?.nonEmptyOrNil, value(.signature))
317    }
318
319    /// The front matter of the file at `path`, read in its type; Org's for a file Denote has
320    /// no type for.
321    public static func frontMatter(ofFile path: String, text: String) -> (title: String?, keywords: [String]?, identifier: String?, signature: String?) {
322        frontMatter(of: text, type: FileType(path: path, text: text) ?? .org)
323    }
324
325    /// The front matter's date in `calendar`'s time zone: an Org timestamp, or for the other
326    /// types `YYYY-MM-DD`, optionally with a time and a UTC offset.
327    public static func date(of text: String, type: FileType = .org, calendar: Calendar = .current) -> Date? {
328        if type == .org {
329            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 }
330            return calendar.date(from: DateComponents(year: Int(match.1), month: Int(match.2), day: Int(match.3),
331                                                      hour: match.4.flatMap { Int($0) } ?? 0, minute: match.5.flatMap { Int($0) } ?? 0))
332        }
333        guard let raw = rawValue(.date, in: text, type: type),
334              let match = raw.firstMatch(of: /^(\d{4})-(\d{2})-(\d{2})(?:[T ](\d{2}):(\d{2})(?::(\d{2}))?)?[ \t]*(Z|[+-]\d{2}:?\d{2})?/) else { return nil }
335        var components = DateComponents(year: Int(match.1), month: Int(match.2), day: Int(match.3),
336                                        hour: match.4.flatMap { Int($0) } ?? 0, minute: match.5.flatMap { Int($0) } ?? 0, second: match.6.flatMap { Int($0) } ?? 0)
337        if let zone = match.7 {
338            let digits = zone.filter(\.isNumber)
339            let minutes = zone == "Z" ? 0 : (Int(digits.prefix(2))! * 60 + Int(digits.suffix(2))!) * (zone.hasPrefix("-") ? -1 : 1)
340            components.timeZone = TimeZone(secondsFromGMT: minutes * 60)
341        }
342        return calendar.date(from: components)
343    }
344
345    /// `denote-rename-file-using-front-matter`: the path the file at `path` takes from its
346    /// front matter's title, keywords and signature, each empty when its line is missing, and
347    /// its text with the front matter rewritten from those values, keywords sorted. Nil for a
348    /// file Denote has no type for, one without front matter, or one without an identifier in
349    /// it or its name.
350    public static func renamed(_ path: String, text: String) -> (path: String, text: String)? {
351        guard let type = FileType(path: path, text: text) else { return nil }
352        let current = name(ofFile: path)
353        let front = frontMatter(of: text, type: type)
354        guard front.title != nil || front.keywords != nil || front.identifier != nil || front.signature != nil,
355              let identifier = front.identifier ?? current.identifier else { return nil }
356        let keywords = Self.keywords(front.keywords ?? []), signature = signature(front.signature ?? ""), title = front.title ?? ""
357        let date = rawValue(.date, in: text, type: type) == nil ? nil : date(of: text, type: type)
358        let file = fileName(identifier: identifier, signature: signature, title: title, keywords: keywords, extension: current.ext)
359        return (((path as NSString).deletingLastPathComponent as NSString).appendingPathComponent(file),
360                rewritingFrontMatter(text, title: title, keywords: keywords, signature: signature, date: date, identifier: identifier, type: type))
361    }
362
363    // MARK: - Links in Markdown and text notes
364
365    /// A link to `link` described by `description`, as `denote-format-link` writes it in the
366    /// file at `path`: `[description](denote:ID)` in Markdown (`denote-md-link-format`), Org's
367    /// bracket link elsewhere, and `[[denote:ID]]` without a description.
368    public static func linkText(_ link: String, description: String, inFile path: String?) -> String {
369        let description = description.trimmingCharacters(in: .whitespacesAndNewlines)
370        guard link.hasPrefix("denote:"), let path, FileType(path: path)?.isMarkdown == true else { return Links.makeString(link, description) }
371        return description.isEmpty ? "[[" + link + "]]" : "[" + description + "](" + link + ")"
372    }
373
374    static let orgLink = try! NSRegularExpression(pattern: #"\[\[(denote:[^\[\]\n]+)\](?:\[[^\]\n]*\])?\]"#)
375    static let markdownLink = try! NSRegularExpression(pattern: #"\[[^\]\n]*\]\((denote:[^()\[\]\s]+)\)"#)
376
377    /// The `denote:` links in a Markdown or text note, as UTF-16 ranges and what they link to:
378    /// `[[denote:ID]]` and `[[denote:ID][description]]` in both, as Denote's link regexps find
379    /// them, and `[description](denote:ID)` in Markdown.
380    public static func links(in text: String, markdown: Bool) -> [(range: Range<Int>, target: String)] {
381        guard text.contains("denote:") else { return [] }
382        let ns = text as NSString, whole = NSRange(location: 0, length: ns.length)
383        return ((markdown ? [orgLink, markdownLink] : [orgLink]).flatMap { $0.matches(in: text, range: whole) })
384            .sorted { $0.range.location < $1.range.location }
385            .map { (Range($0.range)!, ns.substring(with: $0.range(at: 1))) }
386    }
387
388    /// The `denote:` link at `offset` in a Markdown or text note.
389    public static func link(at offset: Int, in text: String, markdown: Bool) -> OrgLink? {
390        links(in: text, markdown: markdown).first { $0.range.contains(offset) || $0.range.upperBound == offset }.map { Links.parse(plain: $0.target) }
391    }
392}
393
394private extension String {
395    var nonEmptyOrNil: String? { isEmpty ? nil : self }
396}
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