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