Sources/OrgCore/Commands/DenoteBlocks.swift

296 lines · 17508 bytes

  1import Foundation
  2
  3// denote-org 0.3's dynamic blocks: `denote-links`, `denote-missing-links`, `denote-backlinks`,
  4// `denote-files`, `denote-files-as-headings` and `denote-sequence`, over the files in `denote-directory`
  5// (`EditingOptions.denoteDirectories`), read from disk. `:excluded-dirs-regexp`,
  6// `:this-heading-only` and `rx` forms for regexps aren't supported.
  7
  8enum DenoteBlocks {
  9    static let names: Set<String> = ["denote-links", "denote-missing-links", "denote-backlinks", "denote-files", "denote-files-as-headings", "denote-sequence"]
 10
 11    /// `denote--directory-get-files`: the files under `directories` whose names have an
 12    /// identifier, without hidden ones or backups, as `directory-files-recursively` lists them:
 13    /// a folder's subfolders' files before its own.
 14    static func files(in directories: [String]) -> [(path: String, relative: String)] {
 15        func walk(_ folder: String, _ relative: String) -> [(String, String)] {
 16            let names = ((try? FileManager.default.contentsOfDirectory(atPath: folder)) ?? []).filter { !$0.hasPrefix(".") }.sorted()
 17            var inner: [(String, String)] = [], own: [(String, String)] = []
 18            for name in names {
 19                let path = (folder as NSString).appendingPathComponent(name), rel = relative.isEmpty ? name : relative + "/" + name
 20                var isDirectory: ObjCBool = false
 21                guard FileManager.default.fileExists(atPath: path, isDirectory: &isDirectory) else { continue }
 22                if isDirectory.boolValue {
 23                    inner += walk(path, rel)
 24                } else if Denote.identifier(ofFile: name) != nil, !name.hasSuffix("~") {
 25                    own.append((path, rel))
 26                }
 27            }
 28            return inner + own
 29        }
 30        return directories.flatMap { walk($0, "") }
 31    }
 32
 33    static func regex(_ regexp: String?) throws -> NSRegularExpression? {
 34        guard let regexp, !regexp.isEmpty else { return nil }
 35        do { return try NSRegularExpression(pattern: EmacsRegex.translate(regexp)) } catch { throw EmacsBuffer.UserError(message: "Invalid regexp \(regexp)") }
 36    }
 37
 38    static func matches(_ regex: NSRegularExpression?, _ text: String) -> Bool {
 39        regex?.firstMatch(in: text, range: NSRange(location: 0, length: (text as NSString).length)) != nil
 40    }
 41
 42    static func read(_ path: String) -> String { (try? String(contentsOfFile: path, encoding: .utf8)) ?? "" }
 43
 44    /// `denote-retrieve-title-or-filename`: an Org file's `#+title`, else the file name's.
 45    static func title(_ path: String) -> String {
 46        if (path as NSString).pathExtension == "org", let title = Denote.frontMatter(of: read(path)).title { return title }
 47        return Denote.name(ofFile: path).title ?? ""
 48    }
 49
 50    /// `denote-link-description-with-signature-and-title`.
 51    static func description(_ path: String) -> String {
 52        let signature = Denote.name(ofFile: path).signature, title = title(path)
 53        switch (signature, title.isEmpty) {
 54        case (let signature?, false): return signature + "  " + title
 55        case (nil, false): return title
 56        case (let signature?, true): return signature
 57        default: return ""
 58        }
 59    }
 60
 61    /// `denote-link--prepare-links` as a list, unsorted.
 62    static func links(_ paths: [String], idOnly: Bool, includeDate: Bool) -> String {
 63        paths.map { path in
 64            let id = Denote.identifier(ofFile: path) ?? ""
 65            var description = description(path)
 66            if includeDate {
 67                let date = id.count >= 8 ? "\(id.prefix(4))-\(id.dropFirst(4).prefix(2))-\(id.dropFirst(6).prefix(2))" : id
 68                description = "\(title(path)) (\(date))"
 69            }
 70            return "- " + (idOnly || description.isEmpty ? "[[denote:\(id)]]" : "[[denote:\(id)][\(description)]]") + "\n"
 71        }.joined()
 72    }
 73
 74    /// `denote-sort-files`: by a file name component (those without it last), by last
 75    /// modified, or kept in identifier order; then reversed with `reverse`.
 76    static func sorted(_ paths: [String], by component: String?, reverse: Bool) -> [String] {
 77        var result = paths
 78        func value(_ path: String) -> String? {
 79            let name = Denote.name(ofFile: path)
 80            switch component {
 81            case "identifier": return name.identifier
 82            case "title": return name.title
 83            case "keywords": return name.keywords.isEmpty ? nil : name.keywords.joined(separator: "_")
 84            case "signature": return name.signature
 85            default: return nil
 86            }
 87        }
 88        switch component {
 89        case "identifier", "title", "keywords", "signature":
 90            result = paths.enumerated().sorted { a, b in
 91                let one = value(a.element), two = value(b.element)
 92                switch (one, two) {
 93                case (nil, _): return a.offset < b.offset && two == nil
 94                case (_, nil): return true
 95                case (let one?, let two?): return one == two ? a.offset < b.offset : one < two
 96                }
 97            }.map(\.element)
 98        case "last-modified":
 99            func modified(_ path: String) -> Date { (try? FileManager.default.attributesOfItem(atPath: path)[.modificationDate] as? Date) ?? .distantPast }
100            result = paths.enumerated().sorted { a, b in
101                let one = modified(a.element), two = modified(b.element)
102                return one == two ? a.offset < b.offset : one > two
103            }.map(\.element)
104        case "random": result.shuffle()
105        default: break
106        }
107        return reverse ? result.reversed() : result
108    }
109
110    /// `denote-org-escape-code-in-region`: `#+` at a line's start behind a zero-width space.
111    static func escaped(_ text: String) -> String {
112        text.replacingOccurrences(of: "(?m)^([ \\t]*)#\\+", with: "$1\u{200B}#+", options: .regularExpression)
113    }
114}
115
116extension EmacsBuffer {
117    /// A denote-org block's new contents.
118    func denoteBlock(_ name: String, paramText: String) throws -> String {
119        let params = try ClockTable.Params(paramText, defaults: [:])
120        if params.values[":this-heading-only"].map({ $0.symbol != "nil" }) == true {
121            throw UserError(message: ":this-heading-only isn't supported")
122        }
123        let all = DenoteBlocks.files(in: options.denoteDirectories ?? [])
124        let current = options.filePath.map { URL(fileURLWithPath: $0).standardizedFileURL.path }
125        let rx = try DenoteBlocks.regex(params.symbol(":regexp")), notRx = try DenoteBlocks.regex(params.symbol(":not-regexp"))
126        let sort = params.symbol(":sort-by-component").flatMap { $0 == "nil" ? nil : $0 }, reverse = params.flag(":reverse-sort")
127        /// `denote-directory-files` with `:omit-current`, then sorted.
128        func files(_ omitCurrent: Bool = true) -> [String] {
129            let found = all.filter { file in
130                !(omitCurrent && file.path == current) && (rx == nil || DenoteBlocks.matches(rx, file.relative)) && !DenoteBlocks.matches(notRx, file.path)
131            }.map(\.path)
132            return DenoteBlocks.sorted(found, by: sort, reverse: reverse)
133        }
134        let blockName = params.symbol(":block-name").map { "#+name: \($0)\n" } ?? ""
135        let idOnly = params.flag(":id-only"), includeDate = params.flag(":include-date")
136        var out: String
137        switch name {
138        case "denote-links":
139            out = blockName + DenoteBlocks.links(files(), idOnly: idOnly, includeDate: includeDate)
140        case "denote-missing-links":
141            // The identifiers this file links to, as `denote-get-links` collects them.
142            let linked = Set(string.matches(of: /\[\[denote:(\d{8}T\d{6})/).map { String($0.1) })
143            out = blockName + DenoteBlocks.links(files().filter { !linked.contains(Denote.identifier(ofFile: $0) ?? "") }, idOnly: idOnly, includeDate: includeDate)
144        case "denote-backlinks":
145            guard let current, let id = Denote.identifier(ofFile: current) else { throw UserError(message: "The file does not have a Denote identifier") }
146            // As the xref search finds them: by path.
147            let linking = all.map(\.path).sorted().filter { path in
148                let text = path == current ? string : DenoteBlocks.read(path)
149                return text.contains("[denote:\(id)]") || text.contains("[denote:\(id)::")
150            }
151            out = DenoteBlocks.links(DenoteBlocks.sorted(linking.filter { !DenoteBlocks.matches(notRx, $0) }, by: sort, reverse: reverse), idOnly: idOnly, includeDate: includeDate)
152        case "denote-files":
153            guard rx != nil else { out = blockName; break }
154            let separator: String
155            switch params.values[":file-separator"] {
156            case nil, .symbol("nil")?: separator = ""
157            case .string(let s)?: separator = s
158            default: separator = "\n\n" + String(repeating: "-", count: 50) + "\n\n\n"
159            }
160            let addLinks = params.values[":add-links"].flatMap { $0.symbol == "nil" ? nil : $0 }
161            let noFrontMatter = params.values[":no-front-matter"].flatMap { $0.symbol == "nil" ? nil : $0 }
162            out = blockName + files().map { path in
163                var text = DenoteBlocks.read(path)
164                if let noFrontMatter {
165                    var lines = text.components(separatedBy: "\n")
166                    if let count = noFrontMatter.integer {
167                        lines.removeFirst(min(count, lines.count))
168                    } else if let blank = lines.firstIndex(of: "") {
169                        lines.removeFirst(blank + 1)
170                    }
171                    text = lines.joined(separator: "\n")
172                }
173                if let addLinks {
174                    let id = Denote.identifier(ofFile: path) ?? "", description = DenoteBlocks.description(path)
175                    let link = addLinks.symbol == "id-only" || description.isEmpty ? "[[denote:\(id)]]" : "[[denote:\(id)][\(description)]]"
176                    text = "- \(link)\n\n" + text.components(separatedBy: "\n").map { $0.isEmpty ? $0 : "  " + $0 }.joined(separator: "\n")
177                }
178                return DenoteBlocks.escaped(text)
179            }.joined(separator: separator)
180        case "denote-sequence":
181            // A note and its descendants down to `:depth` levels, or with `:sequence` "" every
182            // note with a sequence, indented under their parents.
183            let model = DenoteSequence(scheme: options.denoteSequenceScheme)
184            let numbered = DenoteSequence.files(all.map(\.path))
185            let sequence = params.symbol(":sequence") ?? ""
186            var family = numbered
187            if sequence != "" && sequence != ".+" {
188                let children = (try? model.relatives(of: sequence, .allChildren, in: numbered)) ?? []
189                let parent = DenoteSequence.path(of: sequence, in: numbered)
190                family = numbered.filter { $0.path == parent || children.contains($0.path) }
191            }
192            let sorted = family.indices.sorted {
193                let a = model.sortKey(family[$0].sequence), b = model.sortKey(family[$1].sequence)
194                return a == b ? $0 < $1 : a < b
195            }.map { family[$0] }
196            guard let root = sorted.first, let rootDepth = try? model.depth(root.sequence) else { out = ""; break }
197            let maxDepth = params.int(":depth").map { rootDepth + $0 - 1 } ?? Int.max
198            out = blockName + sorted.compactMap { file -> String? in
199                guard let depth = try? model.depth(file.sequence), depth <= maxDepth else { return nil }
200                let id = Denote.identifier(ofFile: file.path) ?? ""
201                return String(repeating: " ", count: 2 * (depth - rootDepth)) + "- [[denote:\(id)][\(file.sequence): \(DenoteBlocks.description(file.path))]]\n"
202            }.joined()
203        default: // denote-files-as-headings
204            guard rx != nil else { out = blockName; break }
205            let addLinks = params.flag(":add-links"), excludeTags = params.flag(":exclude-tags")
206            out = blockName + files().filter { ($0 as NSString).pathExtension == "org" }.map { path in
207                var lines = DenoteBlocks.read(path).components(separatedBy: "\n")
208                func value(_ key: String) -> String? {
209                    lines.first { $0.lowercased().hasPrefix("#+\(key):") }.map { String($0.dropFirst(key.count + 3)).trimmingCharacters(in: .whitespaces) }
210                }
211                let title = value("title"), tags = excludeTags ? "" : value("filetags")
212                if let blank = lines.firstIndex(of: ""), blank + 1 < lines.count { lines.removeFirst(blank + 1) }
213                var body = lines.joined(separator: "\n").replacingOccurrences(of: "(?m)^(\\*+) ", with: "*$1 ", options: .regularExpression)
214                if let title, let tags {
215                    let id = Denote.identifier(ofFile: path) ?? ""
216                    var heading = LineBuffer(addLinks ? "* [[denote:\(id)][\(title)]] \(tags)" : "* \(title) \(tags)", caret: nil)
217                    if !excludeTags { OrgCore.alignTags(&heading, options: options) }
218                    body = heading.string + "\n\n" + body
219                }
220                return DenoteBlocks.escaped(body)
221            }.joined()
222        }
223        // `join-line` at the end: the last newline goes.
224        if out.hasSuffix("\n") { out.removeLast() }
225        return out
226    }
227}
228
229/// `denote-org-dblock-insert-links` and the others: denote-org's questions, then the block
230/// with its parameters, as `org-create-dblock` writes them, updated.
231public struct InsertDenoteBlock: OrgCommand {
232    public enum Kind: String, CaseIterable, Sendable {
233        case links, missingLinks = "missing-links", backlinks, files, filesAsHeadings = "files-as-headings", sequence
234    }
235
236    public let kind: Kind
237    public init(_ kind: Kind) { self.kind = kind }
238    public var id: String { "org.denote.dblock-insert-\(kind.rawValue)" }
239    public var title: String {
240        switch kind {
241        case .links: "Insert Denote Links Block"
242        case .missingLinks: "Insert Denote Missing Links Block"
243        case .backlinks: "Insert Denote Backlinks Block"
244        case .files: "Insert Denote Files Block"
245        case .filesAsHeadings: "Insert Denote Files as Headings Block"
246        case .sequence: "Insert Denote Sequence Block"
247        }
248    }
249    public func applies(in context: EditContext) -> Bool { true }
250
251    static let sortComponents = ["title", "keywords", "signature", "identifier", "random", "last-modified"]
252
253    /// `prin1-to-string` of a string.
254    static func quoted(_ s: String) -> String {
255        "\"" + s.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\"") + "\""
256    }
257
258    public func run(in context: EditContext) -> CommandStep {
259        let answers = context.answers
260        let params: String
261        switch kind {
262        case .links, .missingLinks:
263            guard let regexp = answers["regexp"] else { return .prompt(Self.regexpPrompt) }
264            params = ":regexp \(Self.quoted(regexp)) :not-regexp nil :excluded-dirs-regexp nil :sort-by-component nil :reverse-sort nil :id-only nil :include-date nil"
265        case .backlinks:
266            params = ":excluded-dirs-regexp nil :sort-by-component nil :reverse-sort nil :id-only nil :this-heading-only nil :include-date nil"
267        case .files, .filesAsHeadings:
268            guard let regexp = answers["regexp"] else { return .prompt(Self.regexpPrompt) }
269            guard let sort = answers["sort"] else {
270                return .prompt(Prompt(key: "sort", message: "Sort by file name component: ", choices: Self.sortComponents))
271            }
272            let rest = kind == .files ? ":no-front-matter nil :file-separator nil :add-links nil" : ":add-links nil :exclude-tags nil"
273            params = ":regexp \(Self.quoted(regexp)) :not-regexp nil :excluded-dirs-regexp nil :sort-by-component \(sort.isEmpty ? "nil" : sort) :reverse-sort nil " + rest
274        case .sequence:
275            let files = DenoteSequence.files(DenoteBlocks.files(in: context.options.denoteDirectories ?? []).map(\.path))
276            let labels = files.map { ($0.path as NSString).lastPathComponent }
277            guard let file = answers["sequence"] else {
278                guard !files.isEmpty else { return .failed("There are no sequence notes in the denote-directory") }
279                return .prompt(Prompt(key: "sequence", message: "List descendants of: ", choices: labels))
280            }
281            guard let depthText = answers["depth"] else {
282                return .prompt(Prompt(key: "depth", message: "Maximum relative depth from root node (default 2): ", requireMatch: false))
283            }
284            guard let index = labels.firstIndex(of: file) else { return .failed("No sequence note \(file)") }
285            guard let depth = depthText.isEmpty ? 2 : Int(depthText.trimmingCharacters(in: .whitespaces)) else { return .failed("Please enter a number.") }
286            params = ":sequence \(Self.quoted(files[index].sequence)) :depth \(depth)"
287        }
288        return commitBuffer(context) { buffer in
289            let begin = buffer.createDynamicBlock("denote-\(kind.rawValue) " + params)
290            try buffer.updateDynamicBlock(at: begin)
291            buffer.point = begin
292        }
293    }
294
295    static let regexpPrompt = Prompt(key: "regexp", message: "Match files with the given REGEXP: ", requireMatch: false)
296}