Sources/OrgApp/DenoteSequenceActions.swift
188 lines · 11888 bytes
1import Foundation
2import OrgCore
3import OrgIndex
4
5/// denote-sequence's commands, `app.node.sequence-…`: notes numbered in a hierarchy through
6/// their signatures.
7extension RoamActions {
8 private var sequences: DenoteSequence { DenoteSequence(scheme: OrgPreferences.denoteSequenceScheme()) }
9
10 /// The notes with a sequence, in `denote-directory` order.
11 private func sequenceFiles() -> [(path: String, sequence: String)] {
12 DenoteSequence.files(Denote.files(in: DenoteNote.directories(roots: roots())))
13 }
14
15 /// The open file's sequence.
16 private var currentSequence: (path: String, sequence: String)? {
17 guard let path = session.path, let signature = Denote.name(ofFile: path).signature, DenoteSequence.isSequence(signature) else { return nil }
18 return (path, signature)
19 }
20
21 /// `denote-sequence-file-prompt`: one of `files` by its name.
22 private func chooseSequenceFile(_ message: String, _ files: [(path: String, sequence: String)], _ then: @escaping ((path: String, sequence: String)) -> Void) {
23 guard !files.isEmpty else { return show("There are no sequence notes in the denote-directory") }
24 let labels = files.map { ($0.path as NSString).lastPathComponent }
25 ask(Prompt(key: "sequence", message: message + ": ", choices: labels)) { answer in
26 guard let answer, let index = labels.firstIndex(of: answer) else { return }
27 then(files[index])
28 }
29 }
30
31 /// The current file's sequence, or one asked for, as `denote-sequence--get-current-sequence-or-prompt`.
32 private func currentOrChosen(_ message: String, _ then: @escaping (String) -> Void) {
33 if let current = currentSequence { return then(current.sequence) }
34 chooseSequenceFile(message, sequenceFiles()) { then($0.sequence) }
35 }
36
37 /// `denote` with `denote-use-signature`: asks for the title, then `denote-prompts`.
38 private func newNote(_ sequence: () throws -> String) {
39 let signature: String
40 do { signature = try sequence() } catch { return show("\(error)") }
41 ask(Prompt(key: "title", message: "New file TITLE: ", requireMatch: false)) { title in
42 guard let title else { return }
43 let known: [IndexStore.Node]
44 do { known = try nodes() } catch { return show(error.localizedDescription) }
45 createDenote(title.trimmingCharacters(in: .whitespaces), known: known, signature: signature) { choice in
46 if case .created(let path, _, _) = choice { open(path, (session.text(of: path).map { ($0 as NSString).length }) ?? 0) }
47 }
48 }
49 }
50
51 /// `denote-rename-file` keeping all but the signature: the file renamed with `sequence`
52 /// and its front matter's `#+signature:` set.
53 @discardableResult
54 private func renameSequence(_ path: String, to sequence: String, reopen: Bool) -> String? {
55 guard let text = session.text(of: path) ?? (try? String(contentsOfFile: path, encoding: .utf8)) else { show("Can't read \((path as NSString).lastPathComponent)"); return nil }
56 let name = Denote.name(ofFile: path), front = Denote.frontMatter(of: text)
57 let (target, rewritten) = DenoteNote.renaming(path, text: text, title: front.title ?? name.title?.replacingOccurrences(of: "-", with: " ") ?? "",
58 keywords: front.keywords ?? name.keywords, signature: sequence, date: nil, roots: DenoteNote.directories(roots: roots()))
59 if rewritten != text {
60 if session.openPaths.contains(path) {
61 if case .failed(let message) = session.perform(ReplaceText(old: text, new: rewritten), path: path, at: 0, expect: nil) { show(message); return nil }
62 } else {
63 do { try rewritten.write(toFile: path, atomically: true, encoding: .utf8) } catch { show("Can't write: \(error)"); return nil }
64 }
65 }
66 guard target != path else { return path }
67 guard !FileManager.default.fileExists(atPath: target) else { show("\((target as NSString).lastPathComponent) is already there"); return nil }
68 do {
69 try move(path, to: target)
70 if reopen { open(target, 0) }
71 return target
72 } catch {
73 show("Can't rename: \(error)")
74 return nil
75 }
76 }
77
78 /// `denote-sequence-find-next-sibling` and `-previous-sibling`: the nearest sibling that
79 /// exists in that direction.
80 private func findSibling(of sequence: String, next: Bool, among relatives: [(path: String, sequence: String)]) {
81 let model = sequences
82 guard let inLine = try? model.neighbor(of: sequence, next: next) else {
83 return show("No `\(next ? "next" : "previous")' sibling for sequence `\(sequence)'")
84 }
85 if !relatives.isEmpty, let path = DenoteSequence.path(of: inLine, in: relatives) { return open(path, 0) }
86 // `denote-sequence--keep-sibling-files`: those past where the missing one would sort.
87 let phony = "\u{0}"
88 let all = relatives + [(phony, inLine)]
89 let sorted = all.indices.sorted {
90 let a = model.sortKey(all[$0].sequence), b = model.sortKey(all[$1].sequence)
91 return a == b ? $0 < $1 : a < b
92 }.map { all[$0] }
93 guard let position = sorted.firstIndex(where: { $0.path == phony }) else { return }
94 let remaining = Array(next ? sorted[(position + 1)...] : sorted[..<position])
95 guard !remaining.isEmpty else { return show("No `\(next ? "next" : "previous")' sibling for sequence `\(sequence)'") }
96 findSibling(of: inLine, next: next, among: remaining)
97 }
98
99 func runSequence(_ command: String) {
100 let model = sequences
101 let files = sequenceFiles()
102 let all = files.map(\.sequence)
103 switch command {
104 case "new-parent":
105 newNote { try model.newParent(among: all) }
106 case "new-child", "new-sibling":
107 chooseSequenceFile("Make a new \(command == "new-child" ? "child" : "sibling") of SEQUENCE", files) { file in
108 newNote { command == "new-child" ? try model.newChild(of: file.sequence, among: all) : try model.newSibling(of: file.sequence, among: all) }
109 }
110 case "new-child-of-current", "new-sibling-of-current":
111 let child = command == "new-child-of-current"
112 currentOrChosen("Make a new \(child ? "child" : "sibling") of SEQUENCE") { sequence in
113 newNote { child ? try model.newChild(of: sequence, among: all) : try model.newSibling(of: sequence, among: all) }
114 }
115 case "find":
116 guard let current = currentSequence else { return show("The current file has no sequence") }
117 let relations = DenoteSequence.Relation.allCases
118 ask(Prompt(key: "relation", message: "Find relatives of TYPE: ", choices: relations.map(\.rawValue))) { answer in
119 guard let answer, let relation = DenoteSequence.Relation(rawValue: answer) else { return }
120 let found = ((try? model.relatives(of: current.sequence, relation, in: files)) ?? [])
121 guard !found.isEmpty else { return show("The sequence `\(current.sequence)' has no relatives of type `\(answer)'") }
122 if relation == .parent { return open(found[0], 0) }
123 chooseSequenceFile("Select a relative", files.filter { found.contains($0.path) }) { open($0.path, 0) }
124 }
125 case "next-sibling", "previous-sibling":
126 currentOrChosen("Find the \(command == "next-sibling" ? "next" : "previous") sibling of SEQUENCE") { sequence in
127 let siblings = ((try? model.relatives(of: sequence, .siblings, in: files)) ?? [])
128 findSibling(of: sequence, next: command == "next-sibling", among: files.filter { siblings.contains($0.path) })
129 }
130 case "reparent", "reparent-recursive":
131 guard let path = session.path else { return show("No file is open") }
132 let file = (path as NSString).lastPathComponent
133 chooseSequenceFile("Reparent `\(file)'\(command == "reparent" ? "" : " (recursively)") to be a child of", files) { target in
134 let root = currentSequence?.sequence
135 let newSequence: String
136 do { newSequence = try model.newChild(of: target.sequence, among: all) } catch { return show("\(error)") }
137 let descendants = command == "reparent-recursive" ? root.flatMap { try? model.relatives(of: $0, .allChildren, in: files) } ?? [] : []
138 guard renameSequence(path, to: newSequence, reopen: true) != nil else { return }
139 for child in descendants {
140 guard let root, let sequence = Denote.name(ofFile: child).signature else { continue }
141 let suffix = sequence.hasPrefix(root) ? String(sequence.dropFirst(root.count)) : sequence
142 renameSequence(child, to: newSequence + suffix, reopen: false)
143 }
144 refresh()
145 show("Renamed to \(Denote.signature(newSequence))")
146 }
147 case "rename-as-parent":
148 guard let path = session.path else { return show("No file is open") }
149 guard currentSequence == nil else { return show("The `\((path as NSString).lastPathComponent)' already has a sequence; aborting") }
150 do {
151 if renameSequence(path, to: try model.newParent(among: all), reopen: true) != nil { refresh() }
152 } catch {
153 show("\(error)")
154 }
155 case "convert":
156 guard let current = currentSequence else { return show("The current file has no sequence") }
157 guard let converted = try? model.converted(current.sequence, to: model.scheme), converted != current.sequence else {
158 return show("The sequence already is \(model.scheme.rawValue)")
159 }
160 if renameSequence(current.path, to: converted, reopen: true) != nil { refresh() }
161 case "link":
162 chooseSequenceFile("Link to file with sequence", files) { file in
163 guard let id = Denote.identifier(ofFile: file.path) else { return }
164 let text = (try? String(contentsOfFile: file.path, encoding: .utf8)) ?? ""
165 let title = Denote.frontMatter(of: text).title ?? Denote.name(ofFile: file.path).title ?? ""
166 insertLink("denote:" + id, title.isEmpty ? file.sequence : file.sequence + " " + title)
167 }
168 case "hierarchy":
169 // `denote-sequence-view-hierarchy` as a list: each note under its parent.
170 let ordered = model.sorted(all).compactMap { sequence in files.first { $0.sequence == sequence } }
171 guard !ordered.isEmpty else { return show("There are no sequence notes in the denote-directory") }
172 let labels = ordered.map { file -> String in
173 let depth = (try? model.depth(file.sequence)) ?? 1
174 let text = (try? String(contentsOfFile: file.path, encoding: .utf8)) ?? ""
175 let title = Denote.frontMatter(of: text).title ?? Denote.name(ofFile: file.path).title ?? ""
176 let keywords = Denote.name(ofFile: file.path).keywords.joined(separator: "_")
177 return String(repeating: " ", count: depth - 1) + file.sequence + (title.trimmingCharacters(in: .whitespaces).isEmpty ? "" : " " + title)
178 + (keywords.isEmpty ? "" : " _" + keywords)
179 }
180 ask(Prompt(key: "sequence", message: "Sequence hierarchy: ", choices: labels)) { answer in
181 guard let answer, let index = labels.firstIndex(of: answer) else { return }
182 open(ordered[index].path, 0)
183 }
184 default:
185 show("Unknown command app.node.sequence-\(command)")
186 }
187 }
188}