Commit 942b1aeb78

942b1aeb78c1317dea1c036aeef6d2a71eff4364

parent: 9fcd8f0f4d

Verified · cmc

cmc <hello@cleberg.net> · 2026-11-19 21:02 UTC

Denote: sequences, denote-org blocks, silos, query links and more

- denote-sequence 0.3: new parent/child/sibling notes, relatives, next and
  previous sibling, reparent, rename as parent, convert, link, hierarchy,
  and the denote-sequence-scheme setting.
- denote-org dynamic blocks: denote-links, -missing-links, -backlinks,
  -files, -files-as-headings and -sequence.
- Rename Note (denote-rename-file) with front matter rewriting, and
  Rename Notes in Folder from Front Matter.
- denote-silo: New Note in Silo and Find Note in Silo.
- denote:query-contents: and query-filenames: links.
- Store Link gives denote: links in Denote notes.
- Capture templates with denote = true file into a new note.
- denote-journal-interval; several denote-directory folders.
- Emacs oracle tests for the blocks, sequences and renaming.

Layout: unified · split

Sources/OrgApp/CaptureModel.swift +2 −2
@@ -56,7 +56,7 @@ public enum CaptureTemplates {
5656 groups.append(CaptureGroup(key: key, name: name))
5757 continue
5858 }
59 let fileless = values["id"]?.string != nil || values["clock"]?.bool == true
59 let fileless = values["id"]?.string != nil || values["clock"]?.bool == true || values["denote"]?.bool == true
6060 guard let key = values["key"]?.string, let body = values["template"]?.string, let file = values["file"]?.string ?? (fileless ? "" : nil) else {
6161 problems.append("capture.toml line \(table.line): a template needs key, file and template")
6262 continue
@@ -92,7 +92,7 @@ public enum CaptureTemplates {
9292 prepend: flag("prepend"), immediateFinish: flag("immediate-finish"), emptyLines: lines("empty-lines"),
9393 emptyLinesBefore: lines("empty-lines-before"), emptyLinesAfter: lines("empty-lines-after"),
9494 jumpToCaptured: flag("jump-to-captured"), clockIn: flag("clock-in"), clockKeep: flag("clock-keep"), clockResume: flag("clock-resume"),
95 tableLinePos: values["table-line-pos"]?.string, timePrompt: flag("time-prompt")
95 tableLinePos: values["table-line-pos"]?.string, timePrompt: flag("time-prompt"), denote: flag("denote")
9696 )
9797 templates.append(CaptureTemplate(key: key, name: values["name"]?.string ?? key, kind: kind, target: target, template: body, options: options))
9898 }
Sources/OrgApp/Dailies.swift +25 −4
@@ -27,10 +27,31 @@ public struct Dailies: Sendable, Equatable {
2727 public var keyword: String
2828 /// `denote-journal-title-format`, a `format-time-string` format.
2929 public var title: String
30 /// `denote-journal-interval`: `daily`, `weekly`, `monthly` or `yearly`, how long one
31 /// entry lasts.
32 public var interval: String
3033
31 public init(keyword: String = "journal", title: String = "%A %-e %B %Y %H:%M") {
34 public init(keyword: String = "journal", title: String = "%A %-e %B %Y %H:%M", interval: String = "daily") {
3235 self.keyword = keyword
3336 self.title = title
37 self.interval = interval
38 }
39
40 /// `denote-journal--filename-regexp`: whether an identifier's date is in `day`'s
41 /// interval, weeks starting on Monday.
42 func covers(_ identifier: String, _ day: Date) -> Bool {
43 let date = Denote.identifier(for: day)
44 switch interval {
45 case "monthly": return identifier.hasPrefix(date.prefix(6))
46 case "yearly": return identifier.hasPrefix(date.prefix(4))
47 case "weekly":
48 var calendar = Calendar(identifier: .gregorian)
49 calendar.firstWeekday = 2
50 calendar.timeZone = .current
51 guard let week = calendar.dateInterval(of: .weekOfYear, for: day) else { return false }
52 return (0..<7).contains { identifier.hasPrefix(Denote.identifier(for: week.start.addingTimeInterval(Double($0) * 86400 + 43200)).prefix(8)) }
53 default: return identifier.hasPrefix(date.prefix(8))
54 }
3455 }
3556 }
3657
@@ -48,7 +69,8 @@ public struct Dailies: Sendable, Equatable {
4869 if OrgPreferences.usesDenote(defaults) {
4970 guard let base = DenoteNote.directory(roots: roots, defaults: defaults) else { return nil }
5071 return Dailies(directory: OrgAttach.expand(OrgPreferences.denoteJournalDirectory(defaults), in: base), entry: OrgPreferences.dailiesEntry(defaults),
51 journal: Journal(keyword: Denote.keyword(OrgPreferences.denoteJournalKeyword(defaults)), title: OrgPreferences.denoteJournalTitle(defaults)))
72 journal: Journal(keyword: Denote.keyword(OrgPreferences.denoteJournalKeyword(defaults)), title: OrgPreferences.denoteJournalTitle(defaults),
73 interval: OrgPreferences.denoteJournalInterval(defaults)))
5274 }
5375 let roam = OrgPreferences.roamDirectory(defaults)
5476 guard let base = roam.isEmpty ? roots.first : OrgAttach.expand(roam, in: roots.first ?? NSHomeDirectory()) else { return nil }
@@ -72,8 +94,7 @@ public struct Dailies: Sendable, Equatable {
7294
7395 public func path(for day: Date) -> String {
7496 if let journal {
75 let date = Denote.identifier(for: day).prefix(8)
76 if let found = files().first(where: { Denote.identifier(ofFile: $0)?.hasPrefix(date) == true }) { return found }
97 if let found = files().first(where: { Denote.identifier(ofFile: $0).map { journal.covers($0, day) } == true }) { return found }
7798 let name = Denote.fileName(identifier: Denote.identifier(for: day), title: Self.strftime(journal.title, day), keywords: [journal.keyword])
7899 return (directory as NSString).appendingPathComponent(name)
79100 }
Sources/OrgApp/DenoteCapture.swift added +56
@@ -0,0 +1,56 @@
1import Foundation
2import OrgCore
3
4/// `denote-org-capture`: a capture template with `denote = true` first asks for a new note's
5/// title and the questions `denote-prompts` lists, then files the entry in that note.
6public struct DenoteCapture: Sendable {
7 /// The questions, in order: `title`, then `keywords`, `subdirectory`, `date`, `template`
8 /// and `signature` as `denote-prompts` orders them.
9 public let questions: [Capture.Question]
10 let steps: [String]
11 let roots: [String]
12 let folders: [(label: String, path: String)]
13 let templates: [(key: String, text: String)]
14
15 /// With `paths`, the files whose keywords are offered.
16 public init(roots: [String], paths: [String], defaults: UserDefaults = .standard) {
17 let folders = DenoteNote.directories(roots: roots, defaults: defaults)
18 let choices = DenoteNote.folderChoices(folders)
19 let templates = UserConfig.denoteTemplates(defaults)
20 let keywords = Denote.keywords(paths.flatMap { Denote.name(ofFile: $0).keywords })
21 var steps = ["title"], questions = [Capture.Question(prompt: "New file TITLE", defaultValue: "", choices: [])]
22 for prompt in OrgPreferences.denotePrompts(defaults) where !steps.contains(prompt) {
23 switch prompt {
24 case "keywords": questions.append(Capture.Question(prompt: "New file KEYWORDS", defaultValue: "", choices: keywords))
25 case "subdirectory" where choices.count > 1: questions.append(Capture.Question(prompt: "Select SUBDIRECTORY", defaultValue: ".", choices: choices.map(\.label)))
26 case "date": questions.append(Capture.Question(prompt: "DATE and TIME for note", defaultValue: "", choices: [], kind: .date(withTime: true, inactive: false)))
27 case "template" where !templates.isEmpty: questions.append(Capture.Question(prompt: "Select TEMPLATE key", defaultValue: templates[0].key, choices: templates.map(\.key)))
28 case "signature": questions.append(Capture.Question(prompt: "New file SIGNATURE", defaultValue: "", choices: []))
29 default: continue
30 }
31 steps.append(prompt)
32 }
33 self.steps = steps
34 self.questions = questions
35 self.roots = folders
36 self.folders = choices
37 self.templates = templates
38 }
39
40 /// Makes the note from the first `questions.count` answers and returns its path.
41 public func create(_ answers: [String], now: Date = Date()) throws -> String {
42 guard let root = roots.first else { throw Dailies.Failure("No folder for new notes") }
43 var title = "", keywords: [String] = [], folder = root, date = now, template = "", signature = ""
44 for (step, answer) in zip(steps, answers) {
45 switch step {
46 case "title": title = answer.trimmingCharacters(in: .whitespaces)
47 case "keywords": keywords = answer.split(whereSeparator: { $0 == "," || $0 == ":" || $0.isWhitespace }).map(String.init)
48 case "subdirectory": folder = folders.first { $0.label == answer }?.path ?? root
49 case "date": date = answer.isEmpty ? now : RoamActions.date(answer, now: now) ?? now
50 case "template": template = templates.first { $0.key == answer }?.text ?? ""
51 default: signature = answer
52 }
53 }
54 return try DenoteNote.create(title: title, keywords: keywords, in: folder, roots: roots, now: date, signature: signature, template: template).path
55 }
56}
Sources/OrgApp/DenoteNote.swift +67 −9
@@ -5,10 +5,44 @@ import OrgCore
55/// `denote-directory` or a folder under it, starting with the Org front matter and then the
66/// template.
77public enum DenoteNote {
8 /// `denote-directory`: the setting, else the first folder.
8 /// `denote-directories`: the folders of `denote-directory`, separated by `:`, else the
9 /// first sidebar folder.
10 public static func directories(roots: [String], defaults: UserDefaults = .standard) -> [String] {
11 let folders = paths(OrgPreferences.denoteDirectory(defaults), roots: roots)
12 return folders.isEmpty ? Array(roots.prefix(1)) : folders
13 }
14
15 /// The folder new notes go in: the first of `denote-directory`.
916 public static func directory(roots: [String], defaults: UserDefaults = .standard) -> String? {
10 let denote = OrgPreferences.denoteDirectory(defaults)
11 return denote.isEmpty ? roots.first : OrgAttach.expand(denote, in: roots.first ?? NSHomeDirectory())
17 directories(roots: roots, defaults: defaults).first
18 }
19
20 /// `denote-silo-directories`, separated by `:`; by default `denote-directory`'s folders.
21 public static func silos(roots: [String], defaults: UserDefaults = .standard) -> [String] {
22 let silos = paths(OrgPreferences.denoteSiloDirectories(defaults), roots: roots)
23 return silos.isEmpty ? directories(roots: roots, defaults: defaults) : silos
24 }
25
26 static func paths(_ setting: String, roots: [String]) -> [String] {
27 setting.split(separator: ":").map { $0.trimmingCharacters(in: .whitespaces) }.filter { !$0.isEmpty }
28 .map { OrgAttach.expand($0, in: roots.first ?? NSHomeDirectory()) }
29 }
30
31 /// A folder as the folder prompts show it, under `~` when it's in the home folder.
32 public static func abbreviated(_ path: String) -> String {
33 let home = NSHomeDirectory()
34 return path == home || path.hasPrefix(home + "/") ? "~" + path.dropFirst(home.count) : path
35 }
36
37 /// The `subdirectory` prompt's choices and their folders: `.` and the folders under the
38 /// one root, relative to it, or with several roots, each root and its folders in full.
39 public static func folderChoices(_ roots: [String]) -> [(label: String, path: String)] {
40 if roots.count == 1, let root = roots.first {
41 return [(".", root)] + subdirectories(of: root).map { ($0, (root as NSString).appendingPathComponent($0)) }
42 }
43 return roots.flatMap { root in
44 [root] + subdirectories(of: root).map { (root as NSString).appendingPathComponent($0) }
45 }.map { (abbreviated($0), $0) }
1246 }
1347
1448 /// `denote-directory-subdirectories`: the folders under `root`, relative to it, without
@@ -31,16 +65,40 @@ public enum DenoteNote {
3165 return found
3266 }
3367
68 /// `denote-generate-identifier-as-date`: `date`'s identifier, or the first second after it
69 /// no file under `roots` has.
70 public static func unusedIdentifier(_ date: Date, roots: [String]) -> String {
71 let used = roots.reduce(into: Set<String>()) { $0.formUnion(identifiers(under: $1)) }
72 var stamp = date
73 while used.contains(Denote.identifier(for: stamp)) { stamp += 1 }
74 return Denote.identifier(for: stamp)
75 }
76
77 /// `denote-rename-file` of the file at `path` with `text`: its new path and text, the
78 /// keywords sorted, the identifier kept (or for a file without one, its modification
79 /// time's, unused under `roots`), the front matter rewritten or, without one, added.
80 /// A nil `date` keeps the front matter's.
81 public static func renaming(
82 _ path: String, text: String, title: String, keywords: [String], signature: String, date: Date?, roots: [String]
83 ) -> (path: String, text: String) {
84 let name = Denote.name(ofFile: path), front = Denote.frontMatter(of: text)
85 let modified = (try? FileManager.default.attributesOfItem(atPath: path)[.modificationDate] as? Date) ?? Date()
86 let identifier = name.identifier ?? front.identifier ?? unusedIdentifier(date ?? modified, roots: roots)
87 let keywords = Denote.keywords(keywords), signature = Denote.signature(signature)
88 let target = ((path as NSString).deletingLastPathComponent as NSString).appendingPathComponent(
89 Denote.fileName(identifier: identifier, signature: signature, title: title, keywords: keywords, extension: name.ext.isEmpty ? "org" : name.ext))
90 guard name.ext == "org" || name.ext.isEmpty else { return (target, text) }
91 return (target, Denote.rewritingFrontMatter(text, title: title, keywords: keywords, signature: signature, date: date, identifier: identifier, now: date ?? modified))
92 }
93
3494 /// Makes the note's file in `folder`. Its identifier is `now`'s, or as
3595 /// `denote-generate-identifier-as-date` does, the first second after it no file under
36 /// `root` has; the front matter keeps `now`. Fails rather than replace a file.
96 /// `roots` (by default `folder`) has; the front matter keeps `now`. Fails rather than
97 /// replace a file.
3798 public static func create(
38 title: String, keywords: [String], in folder: String, root: String? = nil, now: Date = Date(), signature: String = "", template: String = ""
99 title: String, keywords: [String], in folder: String, roots: [String] = [], now: Date = Date(), signature: String = "", template: String = ""
39100 ) throws -> (path: String, id: String) {
40 let used = identifiers(under: root ?? folder)
41 var stamp = now
42 while used.contains(Denote.identifier(for: stamp)) { stamp += 1 }
43 let id = Denote.identifier(for: stamp)
101 let id = unusedIdentifier(now, roots: roots.isEmpty ? [folder] : roots)
44102 let keywords = Denote.keywords(keywords)
45103 let signature = Denote.signature(signature)
46104 let name = Denote.fileName(identifier: id, signature: signature, title: title, keywords: keywords)
Sources/OrgApp/DenoteSequenceActions.swift added +185
@@ -0,0 +1,185 @@
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}
Sources/OrgApp/EmacsImport.swift +11
@@ -559,9 +559,20 @@ public struct EmacsImport: Sendable {
559559 add(name, .string(format))
560560 case "org-timer-default-timer":
561561 if let text = value.string { add(name, .string(text)) } else if let number = value.integer { add(name, .string(String(number))) } else { note("not a string or number") }
562 case "denote-directory" where value.elements?.isEmpty == false, "denote-silo-directories":
563 guard let folders = value.elements?.compactMap(\.string), folders.count == value.elements?.count, !folders.contains(where: { $0.contains(":") }) else {
564 return note("not a list of folders without :")
565 }
566 add(name, .string(folders.joined(separator: ":")))
562567 case "denote-directory", "denote-journal-directory", "denote-journal-keyword":
563568 guard let text = value.string else { return note("not a string") }
564569 add(name, .string(text))
570 case "denote-sequence-scheme":
571 guard let scheme = value.symbol, DenoteSequence.Scheme(rawValue: scheme) != nil else { return note("not numeric, alphanumeric or alphanumeric-delimited") }
572 add(name, .string(scheme))
573 case "denote-journal-interval":
574 guard let interval = value.symbol, ["daily", "weekly", "monthly", "yearly"].contains(interval) else { return note("not daily, weekly, monthly or yearly") }
575 add(name, .string(interval))
565576 case "denote-journal-title-format":
566577 let formats = ["day-date-month-year": "%A %-e %B %Y", "day-date-month-year-24h": "%A %-e %B %Y %H:%M",
567578 "day-date-month-year-12h": "%A %-e %B %Y %I:%M %p", "day": "%A"]
Sources/OrgApp/LinkFollow.swift +16 −1
@@ -8,6 +8,8 @@ public enum LinkFollow: Equatable, Sendable {
88 /// For the system to open: a web or mail address, or a file Orgstar doesn't edit.
99 case openExternally(URL)
1010 case message(String)
11 /// Files to choose one of to open: a Denote query link's matches.
12 case choose(prompt: String, paths: [String])
1113}
1214
1315extension DocumentSession {
@@ -30,8 +32,21 @@ extension DocumentSession {
3032 show(location)
3133 return .shown
3234 case "denote":
33 let (identifier, search) = Denote.split(link.path)
3435 let paths = ((try? workspace?.index.files()) ?? []).map(\.path)
36 if let query = Denote.query(link.path) {
37 // `denote-query-contents-link` and `denote-query-filenames-link`: the notes whose
38 // text, or name, the regexp matches.
39 guard let regex = try? NSRegularExpression(pattern: EmacsRegex.translate(query.regexp), options: [.caseInsensitive]) else {
40 return .message("Invalid regexp \(query.regexp)")
41 }
42 let matches = paths.filter { Denote.identifier(ofFile: $0) != nil }.filter { path in
43 let subject = query.contents ? (text(of: path) ?? (try? String(contentsOfFile: path, encoding: .utf8)) ?? "") : (path as NSString).lastPathComponent
44 return regex.firstMatch(in: subject, range: NSRange(location: 0, length: (subject as NSString).length)) != nil
45 }.sorted()
46 guard !matches.isEmpty else { return .message("No notes match \(query.regexp)") }
47 return .choose(prompt: "Notes matching \(query.regexp): ", paths: matches)
48 }
49 let (identifier, search) = Denote.split(link.path)
3550 guard let file = Denote.file(withIdentifier: identifier, in: paths) else {
3651 return .message("No file has the Denote identifier \(identifier)")
3752 }
Sources/OrgApp/OrgPreferences.swift +9 −1
@@ -174,13 +174,21 @@ public enum OrgPreferences {
174174 public static func dailiesEntry(_ defaults: UserDefaults = .standard) -> String { string("dailiesEntry", defaults).nonEmpty ?? "* %?" }
175175 /// Whether the note and daily-note commands follow Denote rather than org-roam.
176176 public static func usesDenote(_ defaults: UserDefaults = .standard) -> Bool { string("notesPackage", defaults) == "denote" }
177 /// `denote-directory`; empty for the first folder.
177 /// `denote-silo-directories`, separated by `:`; empty for `denote-directory`'s.
178 public static func denoteSiloDirectories(_ defaults: UserDefaults = .standard) -> String { string("denoteSiloDirectories", defaults) }
179 /// `denote-directory`, folders separated by `:`; empty for the first folder.
178180 public static func denoteDirectory(_ defaults: UserDefaults = .standard) -> String { string("denoteDirectory", defaults) }
179181 /// `denote-journal-directory`, relative to `denote-directory` unless absolute.
180182 public static func denoteJournalDirectory(_ defaults: UserDefaults = .standard) -> String { string("denoteJournalDirectory", defaults).nonEmpty ?? "journal" }
181183 public static func denoteJournalKeyword(_ defaults: UserDefaults = .standard) -> String { string("denoteJournalKeyword", defaults).nonEmpty ?? "journal" }
182184 /// `denote-journal-title-format`, a `format-time-string` format.
183185 public static func denoteJournalTitle(_ defaults: UserDefaults = .standard) -> String { string("denoteJournalTitle", defaults).nonEmpty ?? "%A %-e %B %Y %H:%M" }
186 /// `denote-journal-interval`.
187 public static func denoteJournalInterval(_ defaults: UserDefaults = .standard) -> String { string("denoteJournalInterval", defaults) }
188 /// `denote-sequence-scheme`.
189 public static func denoteSequenceScheme(_ defaults: UserDefaults = .standard) -> DenoteSequence.Scheme {
190 DenoteSequence.Scheme(rawValue: string("denoteSequenceScheme", defaults)) ?? .numeric
191 }
184192 /// `denote-prompts`: what a new note asks after its title, in order.
185193 public static func denotePrompts(_ defaults: UserDefaults = .standard) -> [String] {
186194 string("denotePrompts", defaults).split(whereSeparator: \.isWhitespace).map(String.init)
Sources/OrgApp/RoamActions.swift +146 −20
@@ -80,6 +80,12 @@ public struct RoamActions {
8080 }
8181 case "app.node.rename-from-front-matter":
8282 renameFromFrontMatter()
83 case "app.node.rename":
84 renameNote()
85 case _ where id.hasPrefix("app.node.sequence-"):
86 runSequence(String(id.dropFirst("app.node.sequence-".count)))
87 case "app.node.rename-folder-from-front-matter":
88 renameFolderFromFrontMatter()
8389 case "app.node.find":
8490 chooseNode("Node: ") { choice in
8591 switch choice {
@@ -87,6 +93,24 @@ public struct RoamActions {
8793 case .created(let path, _, _): open(path, (session.text(of: path).map { ($0 as NSString).length }) ?? 0)
8894 }
8995 }
96 case "app.node.silo-find", "app.node.silo-create":
97 // denote-silo: a folder of `denote-silo-directories` in place of `denote-directory`.
98 let silos = DenoteNote.silos(roots: roots())
99 guard !silos.isEmpty else { return show("No folder for new notes") }
100 ask(Prompt(key: "silo", message: "Select a silo: ", choices: silos.map(DenoteNote.abbreviated))) { answer in
101 guard let answer, let silo = silos.first(where: { DenoteNote.abbreviated($0) == answer }) else { return }
102 let opened: (NodeChoice) -> Void = { choice in
103 switch choice {
104 case .existing(let node): open(node.location.path, node.location.start)
105 case .created(let path, _, _): open(path, (session.text(of: path).map { ($0 as NSString).length }) ?? 0)
106 }
107 }
108 guard id == "app.node.silo-create" else { return chooseNode("Node: ", silo: silo, opened) }
109 ask(Prompt(key: "title", message: "New file TITLE: ", requireMatch: false)) { title in
110 guard let title = title?.trimmingCharacters(in: .whitespaces) else { return }
111 createDenote(title, known: nodes(), silo: silo, opened)
112 }
113 }
90114 case "app.node.insert":
91115 chooseNode("Node: ") { choice in
92116 switch choice {
@@ -156,8 +180,8 @@ public struct RoamActions {
156180 /// `org-roam-node-read`: a node by its title, with its file's name when titles repeat. A
157181 /// title no node has makes a node with it, as org-roam's default capture template does;
158182 /// with Denote, `denote` asks for its keywords and makes the note.
159 private func chooseNode(_ message: String, _ then: @escaping (NodeChoice) -> Void) {
160 let all = nodes()
183 private func chooseNode(_ message: String, silo: String? = nil, _ then: @escaping (NodeChoice) -> Void) {
184 let all = silo.map { silo in nodes().filter { $0.location.path.hasPrefix(silo.hasSuffix("/") ? silo : silo + "/") } } ?? nodes()
161185 let counts = Dictionary(all.map { ($0.title, 1) }, uniquingKeysWith: +)
162186 let labels = all.map { node in
163187 counts[node.title, default: 0] > 1 ? "\(node.title) (\((node.location.path as NSString).lastPathComponent))" : node.title
@@ -167,7 +191,7 @@ public struct RoamActions {
167191 if let index = labels.firstIndex(of: answer) { return then(.existing(all[index])) }
168192 let title = answer.trimmingCharacters(in: .whitespaces)
169193 guard !title.isEmpty else { return }
170 if denote { return createDenote(title, known: all, then) }
194 if denote || silo != nil { return createDenote(title, known: all, silo: silo, then) }
171195 guard let folder = RoamNode.directory(roots: roots()) else { return show("No folder for new nodes") }
172196 do {
173197 let node = try RoamNode.create(title: title, in: folder)
@@ -191,24 +215,33 @@ public struct RoamActions {
191215
192216 /// `denote`: after the title, the questions `denote-prompts` lists, in its order, then the
193217 /// note in `denote-directory` or the folder chosen under it.
194 private func createDenote(_ title: String, known: [IndexStore.Node], _ then: @escaping (NodeChoice) -> Void) {
195 guard let root = DenoteNote.directory(roots: roots()) else { return show("No folder for new notes") }
196 createDenote(title, root: root, prompts: OrgPreferences.denotePrompts(), templates: UserConfig.denoteTemplates(.standard),
197 keywords: Denote.keywords(known.flatMap { Denote.name(ofFile: $0.location.path).keywords }), then)
218 /// In a silo, its folder takes the place of `denote-directory`.
219 /// With `signature`, as `denote-use-signature` sets it: that signature, not asked for.
220 func createDenote(_ title: String, known: [IndexStore.Node], silo: String? = nil, signature: String? = nil, _ then: @escaping (NodeChoice) -> Void) {
221 let folders = silo.map { [$0] } ?? DenoteNote.directories(roots: roots())
222 guard !folders.isEmpty else { return show("No folder for new notes") }
223 var answers = DenoteAnswers()
224 if let signature { answers.signature = signature }
225 createDenote(title, roots: folders, prompts: OrgPreferences.denotePrompts().filter { signature == nil || $0 != "signature" },
226 templates: UserConfig.denoteTemplates(.standard), keywords: Denote.keywords(known.flatMap { Denote.name(ofFile: $0.location.path).keywords }),
227 answers: answers, then)
198228 }
199229
230 /// The note goes in the first of `roots`, or the folder the `subdirectory` question picks
231 /// among them and their folders.
200232 func createDenote(
201 _ title: String, root: String, prompts: [String], templates: [(key: String, text: String)], keywords: [String],
233 _ title: String, roots: [String], prompts: [String], templates: [(key: String, text: String)], keywords: [String],
202234 answers: DenoteAnswers = DenoteAnswers(), _ then: @escaping (NodeChoice) -> Void
203235 ) {
236 let root = roots[0]
204237 func next(_ answers: DenoteAnswers) {
205 createDenote(title, root: root, prompts: Array(prompts.dropFirst()), templates: templates, keywords: keywords, answers: answers, then)
238 createDenote(title, roots: roots, prompts: Array(prompts.dropFirst()), templates: templates, keywords: keywords, answers: answers, then)
206239 }
207240 var answers = answers
208241 switch prompts.first {
209242 case nil:
210243 do {
211 let note = try DenoteNote.create(title: title, keywords: answers.keywords, in: answers.folder ?? root, root: root,
244 let note = try DenoteNote.create(title: title, keywords: answers.keywords, in: answers.folder ?? root, roots: roots,
212245 now: answers.date ?? Date(), signature: answers.signature, template: answers.template)
213246 refresh()
214247 show("Created \((note.path as NSString).lastPathComponent)")
@@ -224,11 +257,11 @@ public struct RoamActions {
224257 next(answers)
225258 }
226259 case "subdirectory":
227 let folders = DenoteNote.subdirectories(of: root)
228 guard !folders.isEmpty else { return next(answers) }
229 ask(Prompt(key: "subdirectory", message: "Select SUBDIRECTORY: ", choices: ["."] + folders)) { answer in
260 let folders = DenoteNote.folderChoices(roots)
261 guard folders.count > 1 else { return next(answers) }
262 ask(Prompt(key: "subdirectory", message: "Select SUBDIRECTORY: ", choices: folders.map(\.label))) { answer in
230263 guard let answer else { return }
231 answers.folder = answer == "." || answer.isEmpty ? root : (root as NSString).appendingPathComponent(answer)
264 answers.folder = folders.first { $0.label == answer }?.path ?? root
232265 next(answers)
233266 }
234267 case "date":
@@ -256,23 +289,116 @@ public struct RoamActions {
256289 }
257290 }
258291
259 /// `denote-rename-file-using-front-matter`: the open file renamed from its title and
260 /// keywords, keeping its identifier and signature.
292 /// `denote-rename-file-using-front-matter`: the open file renamed from its title,
293 /// keywords and signature, keeping its identifier.
261294 func renameFromFrontMatter() {
262295 guard let path = session.path else { return show("No file is open") }
263296 guard let text = session.text(of: path) else { return show("Can't read \((path as NSString).lastPathComponent)") }
264297 guard let target = Denote.renamed(path, text: text) else { return show("Not a Denote note: no front matter or identifier") }
265298 guard target != path else { return show("Nothing to rename") }
299 rename(path, to: target)
300 }
301
302 /// Saves `path`, moves it to `target` and opens it there.
303 func rename(_ path: String, to target: String) {
266304 guard !FileManager.default.fileExists(atPath: target) else { return show("\((target as NSString).lastPathComponent) is already there") }
267 guard session.save(path) else { return show("Can't save \((path as NSString).lastPathComponent)") }
268305 do {
269 try FileManager.default.moveItem(atPath: path, toPath: target)
270 session.kill(path)
306 try move(path, to: target)
271307 refresh()
272308 open(target, 0)
273309 show("Renamed to \((target as NSString).lastPathComponent)")
274310 } catch {
275 show("Can't rename: \(error.localizedDescription)")
311 show("Can't rename: \(error)")
312 }
313 }
314
315 /// Moves a file, saving it first and closing it when it's open.
316 func move(_ path: String, to target: String) throws {
317 if session.openPaths.contains(path) {
318 guard session.save(path) else { throw Dailies.Failure("Can't save \((path as NSString).lastPathComponent)") }
319 }
320 try FileManager.default.moveItem(atPath: path, toPath: target)
321 if session.openPaths.contains(path) { session.kill(path) }
322 }
323
324 /// `denote-rename-file`: the open file's title, keywords, signature and date, as
325 /// `denote-prompts` asks for them, each starting with the current value, then the file
326 /// renamed in its folder and its front matter rewritten. A file without an identifier
327 /// gets one from its modification time; one without front matter gets it at the top.
328 func renameNote() {
329 guard let path = session.path else { return show("No file is open") }
330 guard let text = session.text(of: path) else { return show("Can't read \((path as NSString).lastPathComponent)") }
331 let name = Denote.name(ofFile: path), front = Denote.frontMatter(of: text)
332 var title = front.title ?? name.title?.replacingOccurrences(of: "-", with: " ") ?? ""
333 var keywords = front.keywords ?? name.keywords
334 var signature = name.signature ?? front.signature ?? ""
335 var date: Date?
336 let file = (path as NSString).lastPathComponent
337 func ask(_ prompts: ArraySlice<String>) {
338 switch prompts.first {
339 case nil: finish()
340 case "title":
341 self.ask(Prompt(key: "title", message: "Rename \(file) with TITLE (empty to remove): ", initial: title, requireMatch: false)) { answer in
342 guard let answer else { return }
343 title = answer
344 ask(prompts.dropFirst())
345 }
346 case "keywords":
347 self.ask(Prompt(key: "keywords", message: "Rename \(file) with KEYWORDS (empty to remove): ", initial: keywords.joined(separator: ","), requireMatch: false)) { answer in
348 guard let answer else { return }
349 keywords = answer.split(whereSeparator: { $0 == "," || $0.isWhitespace }).map(String.init)
350 ask(prompts.dropFirst())
351 }
352 case "signature":
353 self.ask(Prompt(key: "signature", message: "Rename \(file) with SIGNATURE (empty to remove): ", initial: signature, requireMatch: false)) { answer in
354 guard let answer else { return }
355 signature = answer
356 ask(prompts.dropFirst())
357 }
358 case "date":
359 self.ask(Prompt(key: "date", message: "Rename \(file) with DATE: ", date: Prompt.DateRead(defaultDate: Denote.date(of: text)))) { answer in
360 guard let answer else { return }
361 date = answer.isEmpty ? nil : Self.date(answer)
362 ask(prompts.dropFirst())
363 }
364 default: ask(prompts.dropFirst())
365 }
366 }
367 func finish() {
368 let (target, rewritten) = DenoteNote.renaming(path, text: text, title: title, keywords: keywords, signature: signature, date: date,
369 roots: DenoteNote.directories(roots: roots()))
370 guard target != path || rewritten != text else { return show("Nothing to rename") }
371 if rewritten != text, case .failed(let message) = session.perform(ReplaceText(old: text, new: rewritten), path: path, at: 0, expect: nil) { return show(message) }
372 guard target != path else { return show("Front matter rewritten") }
373 rename(path, to: target)
374 }
375 ask(ArraySlice(OrgPreferences.denotePrompts()))
376 }
377
378 /// `denote-dired-rename-marked-files-using-front-matter`, with every Denote note in a
379 /// folder of `denote-directory` marked: each renamed from its front matter.
380 func renameFolderFromFrontMatter() {
381 let folders = DenoteNote.folderChoices(DenoteNote.directories(roots: roots()))
382 guard !folders.isEmpty else { return show("No folder for notes") }
383 ask(Prompt(key: "folder", message: "Rename notes in: ", choices: folders.map(\.label))) { answer in
384 guard let answer, let folder = folders.first(where: { $0.label == answer })?.path else { return }
385 let shown = session.path
386 var renamed = 0, problems: [String] = []
387 for name in ((try? FileManager.default.contentsOfDirectory(atPath: folder)) ?? []).sorted() where Denote.identifier(ofFile: name) != nil {
388 let path = (folder as NSString).appendingPathComponent(name)
389 guard let text = session.text(of: path) ?? (try? String(contentsOfFile: path, encoding: .utf8)),
390 let target = Denote.renamed(path, text: text), target != path else { continue }
391 guard !FileManager.default.fileExists(atPath: target) else { problems.append("\((target as NSString).lastPathComponent) is already there"); continue }
392 do {
393 try move(path, to: target)
394 renamed += 1
395 if shown == path { open(target, 0) }
396 } catch {
397 problems.append("\(error)")
398 }
399 }
400 refresh()
401 show(([renamed == 1 ? "Renamed 1 note" : "Renamed \(renamed) notes"] + problems).joined(separator: "; "))
276402 }
277403 }
278404}
Sources/OrgApp/UserConfig.swift +9 −1
@@ -178,13 +178,21 @@ public enum UserConfig {
178178 Setting(section: "", key: "notes-package", defaultsKey: "notesPackage", kind: .choice([("org-roam", "org-roam"), ("denote", "denote")]),
179179 fallback: .string("org-roam"), comment: "whose conventions Find Node, Insert Node Link and the daily-note commands follow: org-roam or denote", legacy: ""),
180180 Setting(section: "", key: "denote-directory", defaultsKey: "denoteDirectory", kind: .string, fallback: .string(""),
181 comment: "the folder new Denote notes go in; empty for the first folder", legacy: ""),
181 comment: "the folders of Denote notes, separated by :, new notes going in the first; empty for the first folder", legacy: ""),
182 Setting(section: "", key: "denote-silo-directories", defaultsKey: "denoteSiloDirectories", kind: .string, fallback: .string(""),
183 comment: "the folders New Note in Silo and Find Note in Silo choose from, separated by :; empty for denote-directory's", legacy: ""),
182184 Setting(section: "", key: "denote-journal-directory", defaultsKey: "denoteJournalDirectory", kind: .string, fallback: .string("journal"),
183185 comment: "the folder denote-journal entries are in, relative to denote-directory", legacy: ""),
184186 Setting(section: "", key: "denote-journal-keyword", defaultsKey: "denoteJournalKeyword", kind: .string, fallback: .string("journal"),
185187 comment: "the keyword journal entries have", legacy: ""),
186188 Setting(section: "", key: "denote-prompts", defaultsKey: "denotePrompts", kind: .string, fallback: .string("title keywords"),
187189 comment: "what a new Denote note asks, in order, separated by spaces: title keywords subdirectory date template signature", legacy: ""),
190 Setting(section: "", key: "denote-sequence-scheme", defaultsKey: "denoteSequenceScheme",
191 kind: .choice([("numeric", "numeric"), ("alphanumeric", "alphanumeric"), ("alphanumeric-delimited", "alphanumeric-delimited")]),
192 fallback: .string("numeric"), comment: "how denote-sequence numbers notes: numeric (1=1=2), alphanumeric (1a2) or alphanumeric-delimited (1=a2)", legacy: ""),
193 Setting(section: "", key: "denote-journal-interval", defaultsKey: "denoteJournalInterval",
194 kind: .choice([("daily", "daily"), ("weekly", "weekly"), ("monthly", "monthly"), ("yearly", "yearly")]), fallback: .string("daily"),
195 comment: "how long one denote-journal entry lasts: daily, weekly, monthly or yearly", legacy: ""),
188196 Setting(section: "", key: "denote-journal-title-format", defaultsKey: "denoteJournalTitle", kind: .string, fallback: .string("%A %-e %B %Y %H:%M"),
189197 comment: "a journal entry's title; a format-time-string format", legacy: ""),
190198 Setting(section: "", key: "auto-fill-mode", defaultsKey: "autoFill", kind: .bool, fallback: .bool(false),
Sources/OrgCore/Capture/Capture.swift +4 −1
@@ -87,12 +87,15 @@ public struct CaptureTemplate: Sendable, Equatable, Identifiable {
8787 public var tableLinePos: String?
8888 /// `:time-prompt`: a date tree asks which day the entry is for.
8989 public var timePrompt = false
90 /// `denote-org-capture`: the entry goes in a new Denote note, asked for first.
91 public var denote = false
9092
9193 public init(
9294 prepend: Bool = false, immediateFinish: Bool = false, emptyLines: Int? = nil, emptyLinesBefore: Int? = nil,
9395 emptyLinesAfter: Int? = nil, jumpToCaptured: Bool = false, clockIn: Bool = false, clockKeep: Bool = false, clockResume: Bool = false,
94 tableLinePos: String? = nil, timePrompt: Bool = false
96 tableLinePos: String? = nil, timePrompt: Bool = false, denote: Bool = false
9597 ) {
98 self.denote = denote
9699 self.tableLinePos = tableLinePos
97100 self.timePrompt = timePrompt
98101 self.prepend = prepend
Sources/OrgCore/Commands/ClockTable.swift +4
@@ -400,6 +400,10 @@ extension EmacsBuffer {
400400 try replaceDynamicBlockContent(at: mark.position, with: table, recalculate: table.range(of: "(?mi)^[ \\t]*#\\+TBLFM:", options: .regularExpression) != nil)
401401 return
402402 }
403 if DenoteBlocks.names.contains(name) {
404 try replaceDynamicBlockContent(at: begin, with: denoteBlock(name, paramText: paramText))
405 return
406 }
403407 guard name == "clocktable" else { throw UserError(message: "Dynamic blocks named \(name) aren't supported") }
404408 var defaults = ClockTable.Params.defaults
405409 defaults[":lang"] = .string(options.exportLanguage)
Sources/OrgCore/Commands/Command.swift +4
@@ -46,6 +46,10 @@ public struct EditingOptions: Sendable, Equatable, Codable {
4646 public var archiveLocation: String?
4747 /// The agenda files (`(org-agenda-files)`), for clock tables over `agenda` scopes; nil for none.
4848 public var agendaFiles: [String]?
49 /// The folders of `denote-directory`, for denote-org's dynamic blocks; nil for none.
50 public var denoteDirectories: [String]?
51 /// `denote-sequence-scheme`, for the `denote-sequence` block.
52 public var denoteSequenceScheme = DenoteSequence.Scheme.numeric
4953 /// The file the buffer visits (`buffer-file-name`); nil for a buffer without one.
5054 public var filePath: String?
5155 /// `org-export-default-language`: the language of exports without `#+LANGUAGE`, and of
Sources/OrgCore/Commands/DenoteBlocks.swift added +227
@@ -0,0 +1,227 @@
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}
Sources/OrgCore/Links/Denote.swift +59 −5
@@ -12,6 +12,17 @@ public enum Denote {
1212 return nil
1313 }
1414
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
1526 /// A `denote:` link's path split at `::` into the identifier and the search.
1627 public static func split(_ path: String) -> (identifier: String, search: String?) {
1728 guard let range = path.range(of: "::") else { return (path, nil) }
@@ -90,12 +101,48 @@ public enum Denote {
90101 /// `denote-org-front-matter`, dated as an inactive Org timestamp. The signature line is
91102 /// left out when there's none.
92103 public static func frontMatter(title: String, date: Date, keywords: [String], identifier: String, signature: String = "", calendar: Calendar = .current) -> String {
93 let c = calendar.dateComponents([.year, .month, .day, .weekday, .hour, .minute], from: date)
94 let day = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"][c.weekday! - 1]
95 let stamp = String(format: "[%04d-%02d-%02d %@ %02d:%02d]", c.year!, c.month!, c.day!, day, c.hour!, c.minute!)
104 lines(title: title, date: date, keywords: keywords, identifier: identifier, signature: signature, calendar: calendar)
105 .compactMap(\.line).map { $0 + "\n" }.joined() + "\n"
106 }
107
108 /// The front matter's lines by key, in its order; nil for a signature line there isn't,
109 /// and for the date when `date` is nil.
110 static func lines(title: String, date: Date?, keywords: [String], identifier: String, signature: String, calendar: Calendar) -> [(key: String, line: String?)] {
111 let stamp = date.map { date in
112 let c = calendar.dateComponents([.year, .month, .day, .weekday, .hour, .minute], from: date)
113 let day = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"][c.weekday! - 1]
114 return String(format: "[%04d-%02d-%02d %@ %02d:%02d]", c.year!, c.month!, c.day!, day, c.hour!, c.minute!)
115 }
96116 let tags = keywords.isEmpty ? "" : ":" + keywords.joined(separator: ":") + ":"
97 return "#+title: \(title)\n#+date: \(stamp)\n#+filetags: \(tags)\n#+identifier: \(identifier)\n"
98 + (signature.isEmpty ? "" : "#+signature: \(signature)\n") + "\n"
117 return [("title", "#+title: \(title)"), ("date", stamp.map { "#+date: \($0)" }), ("filetags", "#+filetags: \(tags)"),
118 ("identifier", "#+identifier: \(identifier)"), ("signature", signature.isEmpty ? nil : "#+signature: \(signature)")]
119 }
120
121 /// `denote-rewrite-front-matter`: `text` with its front matter lines set to these values,
122 /// a missing one added after the one before it, an empty signature's removed, other lines
123 /// kept. A nil `date` keeps the date line. Without front matter, `denote-prepend-front-matter`:
124 /// all of it before the text, dated `date` or `now`.
125 public static func rewritingFrontMatter(
126 _ text: String, title: String, keywords: [String], signature: String, date: Date?, identifier: String, now: Date = Date(), calendar: Calendar = .current
127 ) -> String {
128 var lines = text.components(separatedBy: "\n")
129 let wanted = Self.lines(title: title, date: date, keywords: keywords, identifier: identifier, signature: signature, calendar: calendar)
130 func index(_ key: String) -> Int? {
131 lines.prefix(40).firstIndex { $0.trimmingCharacters(in: .whitespaces).lowercased().hasPrefix("#+" + key + ":") }
132 }
133 guard wanted.contains(where: { index($0.key) != nil }) else {
134 return frontMatter(title: title, date: date ?? now, keywords: keywords, identifier: identifier, signature: signature, calendar: calendar) + text
135 }
136 for (position, item) in wanted.enumerated() {
137 if let at = index(item.key) {
138 if let line = item.line { lines[at] = line } else if item.key == "signature" { lines.remove(at: at) }
139 } else if let line = item.line {
140 let before = wanted[..<position].reversed().compactMap { index($0.key) }.first
141 let after = wanted[(position + 1)...].compactMap { index($0.key) }.first
142 lines.insert(line, at: before.map { $0 + 1 } ?? after ?? 0)
143 }
144 }
145 return lines.joined(separator: "\n")
99146 }
100147
101148 // MARK: - Reading names and front matter
@@ -139,6 +186,13 @@ public enum Denote {
139186 return (value("title"), keywords, value("identifier")?.nonEmptyOrNil, value("signature"))
140187 }
141188
189 /// The front matter's `#+date:`, an Org timestamp, in `calendar`'s time zone.
190 public static func date(of text: String, calendar: Calendar = .current) -> Date? {
191 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 }
192 return calendar.date(from: DateComponents(year: Int(match.1), month: Int(match.2), day: Int(match.3),
193 hour: match.4.flatMap { Int($0) } ?? 0, minute: match.5.flatMap { Int($0) } ?? 0))
194 }
195
142196 /// `denote-rename-file-using-front-matter`: the name the file at `path` takes from its
143197 /// front matter's title, keywords and signature, each empty when its line is missing. Nil
144198 /// when the file has no front matter, or no identifier in it or its name.
Sources/OrgCore/Links/DenoteSequence.swift added +357
@@ -0,0 +1,357 @@
1import Foundation
2
3/// denote-sequence 0.3: a note's place in a hierarchy, kept as its Denote signature. Numeric
4/// sequences (`1=1=2`), alphanumeric ones (`1a2`) and alphanumeric delimited ones (`1=a1b=2`),
5/// each level one deeper. Ported as written, quirks included, so the sequences new notes get
6/// are the ones Emacs gives.
7public struct DenoteSequence: Sendable {
8 public enum Scheme: String, Sendable, CaseIterable, Codable {
9 case numeric, alphanumeric, alphanumericDelimited = "alphanumeric-delimited"
10 }
11
12 /// `denote-sequence-scheme`.
13 public var scheme: Scheme
14
15 public init(scheme: Scheme = .numeric) { self.scheme = scheme }
16
17 struct Failure: Error, CustomStringConvertible {
18 let description: String
19 }
20
21 static func isLetter(_ c: Character) -> Bool { c.isLetter }
22 static func hasLetter(_ s: String) -> Bool { s.contains(where: isLetter) }
23 static func allDigits(_ s: String) -> Bool { !s.isEmpty && s.allSatisfy(\.isASCIIDigit) }
24
25 // MARK: - Schemes
26
27 /// `denote-sequence-numeric-p`.
28 public static func isNumeric(_ s: String) -> Bool {
29 s.contains(where: \.isASCIIDigit) && !hasLetter(s) && !s.hasSuffix("=")
30 }
31
32 /// `denote-sequence-alphanumeric-p`.
33 public static func isAlphanumeric(_ s: String) -> Bool {
34 s.first?.isASCIIDigit == true && !s.contains("=")
35 }
36
37 /// The parts of an alphanumeric delimited sequence: runs of digits, runs of letters, `=`.
38 static func delimitedParts(_ s: String) -> [String] {
39 s.matches(of: /[0-9]+|\p{L}+|=/).map { String($0.0) }
40 }
41
42 /// `denote-sequence-alphanumeric-delimited-p`.
43 public static func isAlphanumericDelimited(_ s: String) -> Bool {
44 if allDigits(s) { return true }
45 guard s.contains("="), !isNumeric(s) else { return false }
46 let parts = delimitedParts(s)
47 // Numbers and letters alternate.
48 var last: Bool?
49 for part in parts where part != "=" {
50 let numeric = part.first!.isASCIIDigit
51 if last == numeric { return false }
52 last = numeric
53 }
54 // One level before the first `=`, then up to three a stretch, all but the last full.
55 var levels: [Int] = [], depth = 0
56 for part in parts {
57 if part == "=" { levels.append(depth); depth = 0 } else { depth += 1 }
58 }
59 levels.append(depth)
60 guard levels[0] == 1, levels.dropFirst().allSatisfy({ $0 <= 3 }) else { return false }
61 if levels.count > 2 { return levels.dropFirst().dropLast().allSatisfy { $0 == 3 } }
62 return true
63 }
64
65 /// `denote-sequence-p`.
66 public static func isSequence(_ s: String) -> Bool { isNumeric(s) || isAlphanumeric(s) || isAlphanumericDelimited(s) }
67
68 /// `denote-sequence-user-selected-scheme-p`.
69 func isInScheme(_ s: String) -> Bool { has(s, scheme) }
70
71 func has(_ s: String, _ scheme: Scheme) -> Bool {
72 switch scheme {
73 case .numeric: Self.isNumeric(s)
74 case .alphanumeric: Self.isAlphanumeric(s)
75 case .alphanumericDelimited: Self.isAlphanumericDelimited(s)
76 }
77 }
78
79 static func isNumericPartial(_ s: String) -> Bool { s.contains(where: \.isASCIIDigit) && !s.contains(where: { $0.isLetter || $0.isPunctuation || $0.isSymbol }) }
80 static func isAlphaPartial(_ s: String) -> Bool { hasLetter(s) && !s.contains(where: { $0.isASCIIDigit || $0.isPunctuation || $0.isSymbol }) }
81
82 /// `denote-sequence-and-scheme-p`: the sequence's scheme.
83 func schemeOf(_ s: String, partial: Bool = false) throws -> Scheme {
84 if !partial, Self.allDigits(s) { return scheme }
85 if !partial, !Self.hasLetter(s), scheme == .numeric { return .numeric }
86 if partial ? Self.isAlphaPartial(s) : Self.isAlphanumeric(s) { return .alphanumeric }
87 if partial ? Self.isNumericPartial(s) : Self.isNumeric(s) { return .numeric }
88 if partial ? (Self.isNumericPartial(s) || Self.isAlphaPartial(s)) : Self.isAlphanumericDelimited(s) { return .alphanumericDelimited }
89 throw Failure(description: "The sequence `\(s)' does not pass `denote-sequence-and-scheme-p'")
90 }
91
92 /// `denote-sequence-split`: a level of depth each.
93 func split(_ s: String, partial: Bool = false) throws -> [String] {
94 switch try schemeOf(s, partial: partial) {
95 case .numeric:
96 return s.split(separator: "=").map(String.init)
97 case .alphanumeric, .alphanumericDelimited:
98 let plain = s.replacingOccurrences(of: "=", with: "")
99 var parts: [String] = []
100 for match in plain.matches(of: /([0-9]+)(\p{L}+)?/) {
101 parts.append(String(match.1))
102 if let letters = match.2 { parts.append(String(letters)) }
103 }
104 return parts.isEmpty ? plain.map(String.init) : parts
105 }
106 }
107
108 /// `denote-sequence-join`.
109 static func join(_ parts: [String], _ scheme: Scheme) -> String {
110 switch scheme {
111 case .numeric: return parts.joined(separator: "=")
112 case .alphanumeric: return parts.joined()
113 case .alphanumericDelimited:
114 var out = ""
115 for (count, part) in parts.enumerated() {
116 out += part
117 if count % 3 == 0, count + 1 < parts.count { out += "=" }
118 }
119 return out
120 }
121 }
122
123 public func depth(_ s: String) throws -> Int { try split(s).count }
124
125 // MARK: - Counting
126
127 /// `denote-sequence-increment-partial`.
128 static func increment(_ s: String) throws -> String {
129 if isNumericPartial(s) { return String((Int(s) ?? 0) + 1) }
130 guard isAlphaPartial(s) else { throw Failure(description: "The string `\(s)' must contain only numbers or letters") }
131 let letters = Array(s)
132 if letters.count == 1 { return letters[0] == "z" ? "za" : String(UnicodeScalar(letters[0].unicodeScalars.first!.value + 1)!) }
133 if letters.last == "z" { return s + "a" }
134 return String(letters.dropLast()) + String(UnicodeScalar(letters.last!.unicodeScalars.first!.value + 1)!)
135 }
136
137 /// `denote-sequence-decrement-partial`; nil below the first.
138 static func decrement(_ s: String) throws -> String? {
139 if isNumericPartial(s) { let n = Int(s) ?? 0; return n == 1 ? nil : String(n - 1) }
140 guard isAlphaPartial(s) else { throw Failure(description: "The string `\(s)' must contain only numbers or letters") }
141 let letters = Array(s)
142 if letters.count == 1 { return letters[0] == "a" ? nil : String(UnicodeScalar(letters[0].unicodeScalars.first!.value - 1)!) }
143 if letters.last == "a" { return String(letters.dropLast()) }
144 return String(letters.dropLast()) + String(UnicodeScalar(letters.last!.unicodeScalars.first!.value - 1)!)
145 }
146
147 /// `denote-sequence--alpha-to-number`.
148 func alphaToNumber(_ s: String) throws -> String {
149 let total = try split(s, partial: true).reduce(0) { sum, letter in
150 let n = Int(letter.unicodeScalars.first!.value) - 96
151 if n > 0, n <= 26 { return sum + n }
152 let times = n / 26, mod = n % 26
153 return sum + times * 26 + (mod > 0 ? mod + 96 : 0)
154 }
155 return String(total)
156 }
157
158 /// `denote-sequence--number-to-alpha`.
159 static func numberToAlpha(_ s: String) -> String {
160 let n = Int(s) ?? 0
161 if n == 0 { return "a" }
162 if n <= 26 { return String(UnicodeScalar(UInt8(n + 96))) }
163 let times = n / 26, mod = n % 26
164 return String(repeating: "z", count: times) + (mod > 0 ? String(UnicodeScalar(UInt8(mod + 96))) : "")
165 }
166
167 /// `denote-sequence-make-conversion` of a whole sequence to `target`.
168 public func converted(_ s: String, to target: Scheme) throws -> String {
169 if target == .numeric {
170 if Self.isNumeric(s) { return s }
171 return Self.join(try split(s).map { Self.isNumericPartial($0) ? $0 : try alphaToNumber($0) }, .numeric)
172 }
173 if Self.isAlphanumeric(s) { return s }
174 let parts = try split(s).enumerated().map { index, part in
175 index % 2 == 0 || Self.isAlphaPartial(part) ? part : Self.numberToAlpha(part)
176 }
177 return Self.join(parts, target)
178 }
179
180 // MARK: - Ordering
181
182 /// `combine-and-quote-strings`' quoting of one string.
183 static func quoted(_ s: String) -> String {
184 guard s.contains(where: { $0 == "\"" || $0 == "\\" || $0 == " " || $0 == "\t" || $0 == "\n" }) else { return s }
185 return "\"" + s.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\"") + "\""
186 }
187
188 static func padded(_ s: String, _ width: Int) -> String { s.count >= width ? s : String(repeating: " ", count: width - s.count) + s }
189
190 enum Kind { case all, parent, sibling, child }
191
192 /// `denote-sequence--pad`: the key sequences sort by.
193 func pad(_ s: String, _ kind: Kind) throws -> String {
194 let parts = try split(s)
195 let list: [String]?, single: String?
196 switch (kind, parts.count > 1) {
197 case (.all, _): (list, single) = (parts, nil)
198 case (.parent, true): (list, single) = (nil, parts[0])
199 case (.sibling, true): (list, single) = (parts, nil)
200 case (.child, true): (list, single) = (nil, parts.last!)
201 default: (list, single) = (nil, s)
202 }
203 if let list { return list.map { Self.quoted(Self.padded($0, 5)) }.joined(separator: "=") }
204 return Self.padded(single!, 32)
205 }
206
207 /// What `denote-sequence-sort-files` compares: the sequence with every level padded.
208 public func sortKey(_ s: String) -> String { (try? pad(s, .all)) ?? s }
209
210 /// `denote-sequence-sort-sequences`.
211 public func sorted(_ sequences: [String]) -> [String] {
212 stableSorted(sequences) { (try? pad($0, .all)) ?? $0 }
213 }
214
215 func stableSorted(_ items: [String], by key: (String) -> String) -> [String] {
216 let keys = items.map(key)
217 return items.indices.sorted { keys[$0] == keys[$1] ? $0 < $1 : keys[$0] < keys[$1] }.map { items[$0] }
218 }
219
220 func largestByOrder(_ sequences: [String], _ kind: Kind) -> String? {
221 stableSorted(sequences) { (try? pad($0, kind)) ?? $0 }.last
222 }
223
224 /// `denote-sequence--get-largest`.
225 func largest(_ sequences: [String], _ kind: Kind) -> String? {
226 guard kind == .child else { return largestByOrder(sequences, kind) }
227 func length(_ s: String) -> Int { scheme == .alphanumeric ? s.count : s.replacingOccurrences(of: "=", with: "").count }
228 guard let longest = sequences.map(length).max() else { return nil }
229 let tied = sequences.filter { length($0) == longest }
230 return tied.count == 1 ? tied[0] : largestByOrder(tied, .child)
231 }
232
233 /// `denote-sequence--get-start`.
234 func start(_ sequence: String? = nil) -> String {
235 guard scheme != .numeric, let last = sequence?.last else { return "1" }
236 return last.isLetter ? "1" : "a"
237 }
238
239 /// `denote-sequence--sequence-prefix-p`.
240 func hasPrefix(_ prefix: [String], _ sequence: String) -> Bool {
241 guard isInScheme(sequence), let parts = try? split(sequence) else { return false }
242 return parts.count >= prefix.count && Array(parts.prefix(prefix.count)) == prefix
243 }
244
245 func withPrefix(_ sequence: String, _ sequences: [String]) -> [String] {
246 guard !sequence.isEmpty, let prefix = try? split(sequence) else { return [] }
247 return sequences.filter { hasPrefix(prefix, $0) }
248 }
249
250 /// `denote-sequence-get-all-sequences-with-max-depth`: each cut to `depth` levels.
251 func withMaxDepth(_ depth: Int, _ sequences: [String]) -> [String] {
252 var seen = Set<String>(), out: [String] = []
253 for s in sequences {
254 guard let parts = try? split(s), parts.count <= depth else { continue }
255 let joined = Self.join(Array(parts.prefix(depth)), scheme)
256 if seen.insert(joined).inserted { out.append(joined) }
257 }
258 return out
259 }
260
261 // MARK: - New sequences
262
263 /// `denote-sequence-get-new` for `parent`: one after the largest first level.
264 public func newParent(among sequences: [String]) throws -> String {
265 guard let top = largest(sequences, .parent) else { return start() }
266 return String((Int(try split(top)[0]) ?? 0) + 1)
267 }
268
269 /// `denote-sequence-get-new` for `child` of `sequence`.
270 public func newChild(of sequence: String, among sequences: [String]) throws -> String {
271 let depth = try self.depth(sequence) + 1
272 let unfiltered = withPrefix(sequence, sequences)
273 guard !unfiltered.isEmpty else { throw Failure(description: "Cannot find sequences given sequence `\(sequence)' using scheme `\(scheme.rawValue)'") }
274 let first = Self.join(try split(sequence) + [start(sequence)], scheme)
275 guard unfiltered.count > 1 else { return first }
276 let cut = withMaxDepth(depth, unfiltered)
277 guard let largest = largest((cut.isEmpty ? unfiltered : cut).filter(isInScheme), .child) else { return first }
278 guard try self.depth(largest) > 1 else { return Self.join(try split(largest) + [start(sequence)], scheme) }
279 var parts = try split(largest)
280 let last = parts.removeLast()
281 return Self.join(parts + [try Self.increment(last)], try schemeOf(largest))
282 }
283
284 /// `denote-sequence-get-new` for `sibling` of `sequence`.
285 public func newSibling(of sequence: String, among sequences: [String]) throws -> String {
286 let parts = try split(sequence)
287 let nested = parts.count > 1
288 let unfiltered = nested ? withPrefix(Self.join(Array(parts.dropLast()), try schemeOf(sequence)), sequences) : sequences
289 let all = withMaxDepth(parts.count, unfiltered).filter(isInScheme)
290 guard all.contains(sequence), let largest = largest(all, nested ? .sibling : .parent) else {
291 throw Failure(description: "Cannot find sequences given sequence `\(sequence)' using scheme `\(scheme.rawValue)'")
292 }
293 guard nested else { return String((Int(largest) ?? 0) + 1) }
294 var largestParts = try split(largest)
295 let last = largestParts.removeLast()
296 return Self.join(largestParts + [try Self.increment(last)], try schemeOf(largest))
297 }
298
299 /// `denote-sequence--infer-sibling`: the sequence one before or after, existing or not.
300 public func neighbor(of sequence: String, next: Bool) throws -> String? {
301 var parts = try split(sequence)
302 let last = parts.removeLast()
303 guard let changed = next ? try Self.increment(last) : try Self.decrement(last) else { return nil }
304 return Self.join(parts + [changed], try schemeOf(sequence))
305 }
306
307 // MARK: - Relatives
308
309 public enum Relation: String, Sendable, CaseIterable {
310 case allParents = "all-parents", parent, siblings, children, allChildren = "all-children"
311 }
312
313 /// `denote-sequence-get-relative` among `files` (path and sequence), in their order.
314 public func relatives(of sequence: String, _ relation: Relation, in files: [(path: String, sequence: String)]) throws -> [String] {
315 let depth = try self.depth(sequence), sequenceScheme = try schemeOf(sequence)
316 let parts = try split(sequence)
317 func common(_ compare: (Int, Int) -> Bool, _ prefix: String) -> [(path: String, sequence: String)] {
318 let pool = prefix.isEmpty ? files : (try? split(prefix)).map { prefix in files.filter { hasPrefix(prefix, $0.sequence) } } ?? []
319 return pool.filter { compare((try? self.depth($0.sequence)) ?? 0, depth) }
320 }
321 switch relation {
322 case .allParents:
323 var likely = Set<String>(), cut = Array(parts.dropLast())
324 while !cut.isEmpty { likely.insert(Self.join(cut, sequenceScheme)); cut.removeLast() }
325 return files.filter { likely.contains($0.sequence) }.map(\.path)
326 case .parent:
327 let parent = Self.join(Array(parts.dropLast()), sequenceScheme)
328 return files.first { $0.sequence == parent }.map { [$0.path] } ?? []
329 case .siblings:
330 let siblings = common(==, Self.join(Array(parts.dropLast()), sequenceScheme))
331 guard let current = Self.path(of: sequence, in: files) else { return [] }
332 return siblings.map(\.path).filter { $0 != current }
333 case .allChildren:
334 return common(>, sequence).map(\.path)
335 case .children:
336 return common(>, sequence).filter { (try? self.depth($0.sequence)) == depth + 1 }.map(\.path)
337 }
338 }
339
340 /// `denote-sequence-get-path`: the file with `sequence`, an Org one when there are several.
341 public static func path(of sequence: String, in files: [(path: String, sequence: String)]) -> String? {
342 let matches = files.filter { $0.sequence == sequence }.map(\.path)
343 return matches.count < 2 ? matches.first : matches.first { ($0 as NSString).pathExtension == "org" } ?? matches.first
344 }
345
346 /// The files with sequences among `paths`: their signatures that are sequences.
347 public static func files(_ paths: [String]) -> [(path: String, sequence: String)] {
348 paths.compactMap { path in
349 guard let signature = Denote.name(ofFile: path).signature, isSequence(signature) else { return nil }
350 return (path, signature)
351 }
352 }
353}
354
355private extension Character {
356 var isASCIIDigit: Bool { isASCII && isNumber }
357}
Sources/OrgCore/Links/LinkStore.swift +19 −3
@@ -50,6 +50,18 @@ extension Links {
5050 return StoredLink(link: link, description: buffer.substring(title.lowerBound, title.upperBound))
5151 }
5252
53 /// `denote-link-ol-store` with `denote-org-store-link-to-heading` nil: a `denote:` link to
54 /// the note at `path`, to the entry at the caret when it has a CUSTOM_ID, described by the
55 /// note's title. Nil when the file name has no identifier.
56 public static func storeDenote(in context: EditContext, path: String) -> StoredLink? {
57 guard let id = Denote.identifier(ofFile: path) else { return nil }
58 let title = Denote.frontMatter(of: context.text).title ?? Denote.name(ofFile: path).title?.replacingOccurrences(of: "-", with: " ") ?? ""
59 let buffer = EmacsBuffer(context.text, point: context.caret, settings: context.tree.settings)
60 buffer.backToHeadingOrPointMin()
61 let custom = buffer.beforeFirstHeading ? nil : buffer.entryProperty("CUSTOM_ID")
62 return StoredLink(link: "denote:" + id + (custom.map { "::#" + $0 } ?? ""), description: title)
63 }
64
5365 /// A `<<target>>` on the caret's line that the caret touches, as `org-in-regexp` finds it.
5466 static func targetAtCaret(_ context: EditContext) -> String? {
5567 let ns = context.text as NSString
@@ -312,7 +324,10 @@ public struct CreateID: OrgCommand {
312324extension EmacsBuffer {
313325 /// The entry's own `ID` when it has non-blank one, from point at its heading (or the
314326 /// start of the file).
315 func entryID() -> String? {
327 func entryID() -> String? { entryProperty("ID") }
328
329 /// A property in the drawer of the entry at point, or before the first heading, the file's.
330 func entryProperty(_ name: String) -> String? {
316331 saveExcursion {
317332 if beforeFirstHeading {
318333 while bolp, lookingAt("^[ \\t]*#[ \\t]") != nil || lookingAt("^[ \\t]*#$") != nil { if forwardLine(1) != 0 { break } }
@@ -322,8 +337,9 @@ extension EmacsBuffer {
322337 }
323338 guard let drawer = looking(Self.propertyDrawerPattern, caseInsensitive: true) else { return nil }
324339 let body = substring(drawer[0]!.lowerBound, drawer[0]!.upperBound)
325 guard let range = body.range(of: "(?m)^[ \\t]*:ID:[ \\t]+(\\S.*?)[ \\t]*$", options: [.regularExpression, .caseInsensitive]) else { return nil }
326 return body[range].replacingOccurrences(of: "^[ \\t]*:[Ii][Dd]:[ \\t]+|[ \\t]+$", with: "", options: .regularExpression)
340 let key = NSRegularExpression.escapedPattern(for: name)
341 guard let range = body.range(of: "(?m)^[ \\t]*:\(key):[ \\t]+(\\S.*?)[ \\t]*$", options: [.regularExpression, .caseInsensitive]) else { return nil }
342 return body[range].replacingOccurrences(of: "^[ \\t]*:\(key):[ \\t]+|[ \\t]+$", with: "", options: [.regularExpression, .caseInsensitive])
327343 }
328344 }
329345}
Sources/OrgEditorAppKit/EditorCommands.swift +18
@@ -122,6 +122,24 @@ public enum EditorCommands {
122122 EditorCommand(id: "app.node.find", title: "Find Node…", action: .app),
123123 EditorCommand(id: "app.node.insert", title: "Insert Node Link…", action: .app),
124124 EditorCommand(id: "app.node.rename-from-front-matter", title: "Rename Note from Front Matter", action: .app),
125 EditorCommand(id: "app.node.rename", title: "Rename Note…", action: .app),
126 EditorCommand(id: "app.node.rename-folder-from-front-matter", title: "Rename Notes in Folder from Front Matter…", action: .app),
127 EditorCommand(id: "app.node.silo-find", title: "Find Note in Silo…", action: .app),
128 EditorCommand(id: "app.node.silo-create", title: "New Note in Silo…", action: .app),
129 EditorCommand(id: "app.node.sequence-new-parent", title: "New Sequence Note…", action: .app),
130 EditorCommand(id: "app.node.sequence-new-child", title: "New Child Sequence Note…", action: .app),
131 EditorCommand(id: "app.node.sequence-new-sibling", title: "New Sibling Sequence Note…", action: .app),
132 EditorCommand(id: "app.node.sequence-new-child-of-current", title: "New Child of This Note…", action: .app),
133 EditorCommand(id: "app.node.sequence-new-sibling-of-current", title: "New Sibling of This Note…", action: .app),
134 EditorCommand(id: "app.node.sequence-find", title: "Find Sequence Relatives…", action: .app),
135 EditorCommand(id: "app.node.sequence-next-sibling", title: "Next Sibling Note", action: .app),
136 EditorCommand(id: "app.node.sequence-previous-sibling", title: "Previous Sibling Note", action: .app),
137 EditorCommand(id: "app.node.sequence-reparent", title: "Reparent Note…", action: .app),
138 EditorCommand(id: "app.node.sequence-reparent-recursive", title: "Reparent Note with Descendants…", action: .app),
139 EditorCommand(id: "app.node.sequence-rename-as-parent", title: "Rename Note as Sequence Parent", action: .app),
140 EditorCommand(id: "app.node.sequence-convert", title: "Convert Note Sequence Scheme", action: .app),
141 EditorCommand(id: "app.node.sequence-link", title: "Insert Sequence Link…", action: .app),
142 EditorCommand(id: "app.node.sequence-hierarchy", title: "Sequence Hierarchy…", action: .app),
125143 EditorCommand(id: "app.attach.attach", title: "Attach File…", action: .app),
126144 EditorCommand(id: "app.attach.move", title: "Attach File by Moving…", action: .app),
127145 EditorCommand(id: "app.attach.link", title: "Attach File as Hard Link…", action: .app),
Sources/Orgstar/CaptureView.swift +26 −3
@@ -17,6 +17,10 @@ struct CaptureView: View {
1717 @State private var groups: [CaptureGroup] = []
1818 /// The day `:time-prompt` asked for.
1919 @State private var treeDate: Date?
20 /// A `denote = true` template's note: its questions, their answers, and once made, its file.
21 @State private var denote: DenoteCapture?
22 @State private var denoteAnswers: [String] = []
23 @State private var denoteFile: String?
2024 @State private var problem: String?
2125 @State private var template: CaptureTemplate?
2226 @State private var questions: [Capture.Question] = []
@@ -136,6 +140,7 @@ struct CaptureView: View {
136140 }
137141
138142 static func target(_ template: CaptureTemplate) -> String {
143 if template.options.denote { return "a new Denote note" }
139144 let file = (template.target.file as NSString).lastPathComponent
140145 switch template.target {
141146 case .file, .heading: return file
@@ -198,7 +203,9 @@ struct CaptureView: View {
198203 for heading in DocumentModel(tree: OrgParser.parse(text)).headings { for tag in heading.localTags where !tags.contains(tag) { tags.append(tag) } }
199204 context.fileTags = tags
200205 }
201 questions = (asksTreeDate(chosen) ? [Self.treeQuestion] : []) + Capture.questions(chosen.template, context: context)
206 denote = chosen.options.denote ? DenoteCapture(roots: workspace.rootPaths, paths: workspace.files.map(\.path)) : nil
207 denoteFile = nil
208 questions = (denote?.questions ?? []) + (asksTreeDate(chosen) ? [Self.treeQuestion] : []) + Capture.questions(chosen.template, context: context)
202209 answers = questions.map { _ in "" }
203210 if questions.isEmpty { expand() }
204211 }
@@ -211,6 +218,10 @@ struct CaptureView: View {
211218 private func expand() {
212219 guard let template else { return }
213220 var answers = answers
221 if let denote {
222 denoteAnswers = Array(answers.prefix(denote.questions.count))
223 answers.removeFirst(min(denote.questions.count, answers.count))
224 }
214225 if asksTreeDate(template) {
215226 treeDate = Capture.treeDate(answers.removeFirst(), now: Date())
216227 }
@@ -247,8 +258,20 @@ struct CaptureView: View {
247258 guard let template else { return }
248259 let opened = context.now
249260 let now = Date()
250 let placed = template.resolved(workspace: workspace, session: session, clock: clock).flatMap { resolved in
251 session.capture(text, template: resolved.template, root: workspace.rootPaths.first, file: resolved.file, now: captureDate(now))
261 let placed: Result<(path: String, offset: Int), CaptureError>
262 if let denote {
263 do {
264 let file = try denoteFile ?? denote.create(denoteAnswers, now: now)
265 if denoteFile == nil { Task { await workspace.refresh() } }
266 denoteFile = file
267 placed = session.capture(text, template: template, root: workspace.rootPaths.first, file: file, now: captureDate(now))
268 } catch {
269 placed = .failure(CaptureError(message: "Can't make the note: \(error)"))
270 }
271 } else {
272 placed = template.resolved(workspace: workspace, session: session, clock: clock).flatMap { resolved in
273 session.capture(text, template: resolved.template, root: workspace.rootPaths.first, file: resolved.file, now: captureDate(now))
274 }
252275 }
253276 switch placed {
254277 case .failure(let error):
Sources/Orgstar/ContentView.swift +7 −3
@@ -71,6 +71,8 @@ struct ContentView: View {
7171 )
7272 // The agenda files, for clock tables over `agenda` scopes.
7373 options.agendaFiles = workspace.agendaFilePaths()
74 options.denoteDirectories = DenoteNote.directories(roots: workspace.rootPaths)
75 options.denoteSequenceScheme = OrgPreferences.denoteSequenceScheme()
7476 options.timer = TimerModel.shared.timer
7577 return options
7678 }
@@ -722,7 +724,7 @@ struct ContentView: View {
722724 apply: { applyText($0, caret: $1) }, show: { [commands] in commands.show($0) }, ask: { [commands] in commands.ask($0, reply: $1) },
723725 storeLink: { [commands] in _ = StoredLink.add($0, to: &commands.storedLinks) },
724726 open: { [session, workspace, commands] file in
725 if let message = LinkOpener.open(OrgLink(type: "file", path: file, raw: "file:" + file), session: session, workspace: workspace) { commands.show(message) }
727 if let message = LinkOpener.open(OrgLink(type: "file", path: file, raw: "file:" + file), session: session, workspace: workspace, ask: commands.ask) { commands.show(message) }
726728 },
727729 reveal: { NSWorkspace.shared.open(URL(fileURLWithPath: $0, isDirectory: true)) },
728730 pick: { method in
@@ -856,7 +858,7 @@ struct ContentView: View {
856858 private func runExternal(_ request: ExternalRequest) {
857859 switch request {
858860 case .openLink(let link):
859 if let message = LinkOpener.open(link, session: session, workspace: workspace) { commands.show(message) }
861 if let message = LinkOpener.open(link, session: session, workspace: workspace, ask: commands.ask) { commands.show(message) }
860862 // `org-occur` for a regexp link, once the editor shows the file.
861863 if let regexp = Links.regexpSearch(link) {
862864 DispatchQueue.main.async { commands.editor?.perform(SparseTreeCommand(), answers: ["sparse": "/", "regexp": regexp]) }
@@ -1125,7 +1127,9 @@ struct ContentView: View {
11251127 commands.editor?.perform(InsertLink(stored: commands.storedLinks, file: session.path))
11261128 case "org.link.store":
11271129 guard let editor = commands.editor, let path = session.path else { return commands.show("No method for storing a link from this buffer") }
1128 commands.storeLink(Links.store(in: editor.context(), path: Links.abbreviate(path, home: NSHomeDirectory())))
1130 let context = editor.context()
1131 let denote = OrgPreferences.usesDenote() ? Links.storeDenote(in: context, path: path) : nil
1132 commands.storeLink(denote ?? Links.store(in: context, path: Links.abbreviate(path, home: NSHomeDirectory())))
11291133 case "org.id.store-link":
11301134 guard let editor = commands.editor, let path = session.path else { return }
11311135 if case .commit = editor.perform(CreateID()),
Sources/Orgstar/LinkOpener.swift +9 −1
@@ -6,13 +6,21 @@ import OrgCore
66@MainActor
77enum LinkOpener {
88 /// Returns a message when the link can't be followed.
9 static func open(_ link: OrgLink, session: DocumentSession, workspace: WorkspaceModel) -> String? {
9 /// `ask` picks among a query link's matches.
10 static func open(_ link: OrgLink, session: DocumentSession, workspace: WorkspaceModel, ask: @escaping (Prompt, @escaping (String?) -> Void) -> Void) -> String? {
1011 switch session.follow(link, workspace: workspace, isText: FileTypes.isText) {
1112 case .shown: return nil
1213 case .openExternally(let url):
1314 NSWorkspace.shared.open(url)
1415 return nil
1516 case .message(let message): return message
17 case .choose(let prompt, let paths):
18 let labels = paths.map { ($0 as NSString).lastPathComponent }
19 ask(Prompt(key: "file", message: prompt, choices: labels)) { answer in
20 guard let answer, let index = labels.firstIndex(of: answer) else { return }
21 _ = open(OrgLink(type: "file", path: paths[index], raw: "file:" + paths[index]), session: session, workspace: workspace, ask: ask)
22 }
23 return nil
1624 }
1725 }
1826}
Sources/OrgstarMobile/CaptureScreen.swift +25 −3
@@ -18,6 +18,10 @@ struct CaptureScreen: View {
1818 @State private var groups: [CaptureGroup] = []
1919 /// The day `:time-prompt` asked for.
2020 @State private var treeDate: Date?
21 /// A `denote = true` template's note: its questions, their answers, and once made, its file.
22 @State private var denote: DenoteCapture?
23 @State private var denoteAnswers: [String] = []
24 @State private var denoteFile: String?
2125 /// The filed entry, while its refile target is picked.
2226 @State private var refiling: RefileEntry?
2327 @State private var key: String?
@@ -127,7 +131,9 @@ struct CaptureScreen: View {
127131 for heading in DocumentModel(tree: OrgParser.parse(source)).headings { for tag in heading.localTags where !tags.contains(tag) { tags.append(tag) } }
128132 context.fileTags = tags
129133 }
130 questions = (asksTreeDate(template) ? [Self.treeQuestion] : []) + Capture.questions(template.template, context: context)
134 denote = template.options.denote ? DenoteCapture(roots: workspace.rootPaths, paths: workspace.files.map(\.path)) : nil
135 denoteFile = nil
136 questions = (denote?.questions ?? []) + (asksTreeDate(template) ? [Self.treeQuestion] : []) + Capture.questions(template.template, context: context)
131137 answers = questions.map { _ in "" }
132138 treeDate = nil
133139 editing = false
@@ -146,6 +152,10 @@ struct CaptureScreen: View {
146152 private func fill() {
147153 guard let template else { return }
148154 var answers = answers
155 if let denote {
156 denoteAnswers = Array(answers.prefix(denote.questions.count))
157 answers.removeFirst(min(denote.questions.count, answers.count))
158 }
149159 if asksTreeDate(template) { treeDate = Capture.treeDate(answers.removeFirst(), now: Date()) }
150160 context.now = captureDate
151161 switch Capture.fill(template.template, context: context, answers: answers) {
@@ -186,8 +196,20 @@ struct CaptureScreen: View {
186196 private func file(refile: Bool = false) {
187197 guard let template else { return }
188198 let now = Date()
189 let placed = template.resolved(workspace: workspace, session: session, clock: clock).flatMap { resolved in
190 session.capture(text, template: resolved.template, root: workspace.rootPaths.first, file: resolved.file, now: treeDate ?? request.day.map(Self.date) ?? now)
199 let placed: Result<(path: String, offset: Int), CaptureError>
200 if let denote {
201 do {
202 let file = try denoteFile ?? denote.create(denoteAnswers, now: now)
203 if denoteFile == nil { Task { await workspace.refresh() } }
204 denoteFile = file
205 placed = session.capture(text, template: template, root: workspace.rootPaths.first, file: file, now: treeDate ?? request.day.map(Self.date) ?? now)
206 } catch {
207 placed = .failure(CaptureError(message: "Can't make the note: \(error)"))
208 }
209 } else {
210 placed = template.resolved(workspace: workspace, session: session, clock: clock).flatMap { resolved in
211 session.capture(text, template: resolved.template, root: workspace.rootPaths.first, file: resolved.file, now: treeDate ?? request.day.map(Self.date) ?? now)
212 }
191213 }
192214 switch placed {
193215 case .failure(let error):
Sources/OrgstarMobile/EditorScreen.swift +29 −1
@@ -45,6 +45,8 @@ struct EditorScreen: View {
4545 var options = session.options
4646 options.filePath = path
4747 options.agendaFiles = workspace.agendaFilePaths()
48 options.denoteDirectories = DenoteNote.directories(roots: workspace.rootPaths)
49 options.denoteSequenceScheme = OrgPreferences.denoteSequenceScheme()
4850 options.timer = TimerModel.shared.timer
4951 return options
5052 }
@@ -333,7 +335,9 @@ struct EditorScreen: View {
333335 guard let editor else { return }
334336 switch id {
335337 case "org.link.store":
336 message = StoredLink.add(Links.store(in: editor.editContext(), path: Links.abbreviate(path, home: NSHomeDirectory())), to: &model.storedLinks)
338 let context = editor.editContext()
339 let denote = OrgPreferences.usesDenote() ? Links.storeDenote(in: context, path: path) : nil
340 message = StoredLink.add(denote ?? Links.store(in: context, path: Links.abbreviate(path, home: NSHomeDirectory())), to: &model.storedLinks)
337341 case "org.id.store-link":
338342 if case .commit = editor.perform(CreateID()),
339343 let link = Links.storeID(in: editor.editContext(), fileName: (path as NSString).lastPathComponent) {
@@ -475,6 +479,12 @@ extension EditorScreen {
475479 model.openRequest = .offset(target, caret)
476480 case .openExternally(let url): if url.isFileURL { previewed = url } else { openURL(url) }
477481 case .message(let text): message = text
482 case .choose(let question, let paths):
483 let labels = paths.map { ($0 as NSString).lastPathComponent }
484 prompt = PromptRequest(prompt: Prompt(key: "file", message: question, choices: labels)) { answer in
485 guard let answer, let index = labels.firstIndex(of: answer) else { return }
486 follow(OrgLink(type: "file", path: paths[index], raw: "file:" + paths[index]))
487 }
478488 }
479489 }
480490
@@ -932,6 +942,24 @@ struct CommandPalette: View {
932942 ("app.crypt.encrypt-entries", "Encrypt Tagged Entries…"), ("app.crypt.forget-passphrase", "Forget Encryption Passphrase"),
933943 ("app.backlinks", "Show Backlinks"), ("app.node.find", "Find Node…"), ("app.node.insert", "Insert Node Link…"),
934944 ("app.node.rename-from-front-matter", "Rename Note from Front Matter"),
945 ("app.node.rename", "Rename Note…"),
946 ("app.node.rename-folder-from-front-matter", "Rename Notes in Folder from Front Matter…"),
947 ("app.node.silo-find", "Find Note in Silo…"),
948 ("app.node.silo-create", "New Note in Silo…"),
949 ("app.node.sequence-new-parent", "New Sequence Note…"),
950 ("app.node.sequence-new-child", "New Child Sequence Note…"),
951 ("app.node.sequence-new-sibling", "New Sibling Sequence Note…"),
952 ("app.node.sequence-new-child-of-current", "New Child of This Note…"),
953 ("app.node.sequence-new-sibling-of-current", "New Sibling of This Note…"),
954 ("app.node.sequence-find", "Find Sequence Relatives…"),
955 ("app.node.sequence-next-sibling", "Next Sibling Note"),
956 ("app.node.sequence-previous-sibling", "Previous Sibling Note"),
957 ("app.node.sequence-reparent", "Reparent Note…"),
958 ("app.node.sequence-reparent-recursive", "Reparent Note with Descendants…"),
959 ("app.node.sequence-rename-as-parent", "Rename Note as Sequence Parent"),
960 ("app.node.sequence-convert", "Convert Note Sequence Scheme"),
961 ("app.node.sequence-link", "Insert Sequence Link…"),
962 ("app.node.sequence-hierarchy", "Sequence Hierarchy…"),
935963 ("app.dailies.today", "Go to Today's Daily Note"), ("app.dailies.yesterday", "Go to Yesterday's Daily Note"),
936964 ("app.dailies.tomorrow", "Go to Tomorrow's Daily Note"), ("app.dailies.date", "Go to Daily Note for Date…"),
937965 ("app.dailies.capture-today", "Capture to Today's Daily Note"), ("app.dailies.capture-yesterday", "Capture to Yesterday's Daily Note"),
Sources/OrgstarMobile/MobileEditor.swift +1
@@ -407,6 +407,7 @@ final class MobileEditor: NSObject, DocumentBuffer {
407407 "app.attach.new", "app.attach.open", "app.attach.reveal", "app.attach.delete", "app.attach.delete-all", "app.attach.sync",
408408 "app.attach.set-directory", "app.attach.unset-directory", "app.backlinks", "app.node.find", "app.node.insert",
409409 "app.node.rename-from-front-matter": return onAppCommand != nil
410 case _ where id.hasPrefix("app.node."): return onAppCommand != nil
410411 case _ where id.hasPrefix("app.dailies."): return onAppCommand != nil
411412 case "app.crypt.encrypt-entry": return onAppCommand != nil && OrgCrypt.heading(context.text, at: context.caret) != nil && OrgCrypt.encryptedRange(context.text, at: context.caret) == nil
412413 case "app.crypt.open-entry", "app.crypt.decrypt-entry": return onAppCommand != nil && OrgCrypt.encryptedRange(context.text, at: context.caret) != nil
Sources/OrgstarMobile/ReaderScreen.swift +1
@@ -382,6 +382,7 @@ struct ReaderScreen: View {
382382 }
383383 case .openExternally(let target): openURL(target)
384384 case .message(let text): message = text
385 case .choose(let question, let paths): message = question + paths.map { ($0 as NSString).lastPathComponent }.joined(separator: ", ")
385386 }
386387 return .handled
387388 }
Tests/OrgAppTests/AppTests.swift +5 −1
@@ -1426,7 +1426,7 @@ struct LinkFollowTests {
14261426 let notes = try Folder()
14271427 let a = try notes.write("a.org", "* Start\n")
14281428 let note = try notes.write("sub/20261119T120000--a-note__kw.org", "#+title: A note\n* Inside\n:PROPERTIES:\n:CUSTOM_ID: in\n:END:\n")
1429 _ = try notes.write("20261119T120000--a-note.pdf", "pdf")
1429 let pdf = try notes.write("20261119T120000--a-note.pdf", "pdf")
14301430 let workspace = try WorkspaceModel(directory: nil)
14311431 try await workspace.addRoot(notes.url)
14321432 let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
@@ -1438,6 +1438,10 @@ struct LinkFollowTests {
14381438 #expect(follow("denote:20261119T120000::#in") == .shown && session.path == note.path)
14391439 #expect(session.revealRequest?.offset == (try String(contentsOfFile: note.path, encoding: .utf8) as NSString).range(of: "* Inside").location)
14401440 #expect(follow("denote:20200101T000000") == .message("No file has the Denote identifier 20200101T000000"))
1441 // Query links: the notes whose text or name the regexp matches.
1442 #expect(follow("denote:query-contents:INSIDE") == .choose(prompt: "Notes matching INSIDE: ", paths: [note.path]))
1443 #expect(follow("denote:query-filenames:a-no+te") == .choose(prompt: "Notes matching a-no+te: ", paths: [pdf.path, note.path].sorted()))
1444 #expect(follow("denote:query-contents:Start") == .message("No notes match Start"))
14411445 }
14421446
14431447 @Test func followsAttachmentAndRadioLinks() throws {
Tests/OrgAppTests/DailiesTests.swift +149 −2
@@ -72,6 +72,23 @@ struct DailiesTests {
7272 #expect(try (journal.neighbor(of: made.path, by: -1) as NSString).lastPathComponent == "20261009T120000--friday-9-october-2026-1200__journal.org")
7373 }
7474
75 /// `denote-journal-interval`: one entry a week (Monday to Sunday), month or year.
76 @Test func denoteJournalIntervals() throws {
77 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-journal-\(UUID().uuidString)").resolvingSymlinksInPath()
78 defer { try? FileManager.default.removeItem(at: folder) }
79 try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
80 let entry = folder.appendingPathComponent("20261005T080000--monday__journal.org").path
81 try "x".write(toFile: entry, atomically: true, encoding: .utf8)
82 func found(_ interval: String, _ days: Int) -> Bool {
83 Dailies(directory: folder.path, journal: Dailies.Journal(interval: interval)).path(for: Calendar.current.date(byAdding: .day, value: days, to: Self.day)!) == entry
84 }
85 // Self.day is Sunday 11 October 2026.
86 #expect(found("weekly", 0) && found("weekly", -6) && !found("weekly", 1) && !found("weekly", -7))
87 #expect(!found("daily", 0) && found("daily", -6))
88 #expect(found("monthly", 20) && !found("monthly", 21))
89 #expect(found("yearly", 81) && !found("yearly", 82))
90 }
91
7592 @Test func newDenoteNote() throws {
7693 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-denote-\(UUID().uuidString)").path
7794 defer { try? FileManager.default.removeItem(atPath: folder) }
@@ -82,13 +99,143 @@ struct DailiesTests {
8299 let again = try DenoteNote.create(title: "Field Notes", keywords: ["work", "ideas"], in: folder, now: Self.day)
83100 #expect((again.path as NSString).lastPathComponent == "20261011T120001--field-notes__ideas_work.org")
84101 let sub = (folder as NSString).appendingPathComponent("projects")
85 let other = try DenoteNote.create(title: "Plan", keywords: [], in: sub, root: folder, now: Self.day, signature: "Two Words", template: "* Goals\n")
102 let other = try DenoteNote.create(title: "Plan", keywords: [], in: sub, roots: [folder], now: Self.day, signature: "Two Words", template: "* Goals\n")
86103 #expect((other.path as NSString).lastPathComponent == "20261011T120002==two=words--plan.org")
87104 #expect(try String(contentsOfFile: other.path, encoding: .utf8)
88105 == "#+title: Plan\n#+date: [2026-10-11 Sun 12:00]\n#+filetags: \n#+identifier: 20261011T120002\n#+signature: two=words\n\n* Goals\n")
89106 #expect(DenoteNote.subdirectories(of: folder) == ["projects"])
90107 }
91108
109 /// A RoamActions on `folder` that answers each prompt from `answers` by key, recording
110 /// what it asked, what it opened and showed, and links inserted.
111 @MainActor
112 final class Harness {
113 let folder: URL
114 let session: DocumentSession
115 var answers: [String: String] = [:]
116 var asked: [Prompt] = []
117 var opened: [String] = []
118 var shown: [String] = []
119 var links: [(String, String)] = []
120 init() throws {
121 folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-denote-\(UUID().uuidString)").resolvingSymlinksInPath()
122 try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
123 session = DocumentSession(recovery: FileRecoveryStore(directory: folder.appendingPathComponent(".r")))
124 }
125 deinit { try? FileManager.default.removeItem(at: folder) }
126 var actions: RoamActions {
127 RoamActions(session: session, roots: { [self.folder.path] }, nodes: { [] }, show: { self.shown.append($0) },
128 ask: { prompt, reply in self.asked.append(prompt); reply(self.answers[prompt.key]) },
129 open: { path, _ in self.opened.append(path); self.session.open(path) }, insertLink: { self.links.append(($0, $1)) }, refresh: {})
130 }
131 @discardableResult
132 func write(_ name: String, _ text: String) throws -> String {
133 let url = folder.appendingPathComponent(name)
134 try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)
135 try text.write(to: url, atomically: true, encoding: .utf8)
136 return url.path
137 }
138 func names() -> [String] { ((try? FileManager.default.contentsOfDirectory(atPath: folder.path)) ?? []).filter { !$0.hasPrefix(".") }.sorted() }
139 }
140
141 /// `denote-rename-file`: the questions start with the current values; the file and its
142 /// front matter change.
143 @MainActor
144 @Test func renamesByPrompting() throws {
145 let h = try Harness()
146 let path = try h.write("20261011T120000--old__x.org", "#+title: Old\n#+date: [2026-10-11 Sun 12:00]\n#+filetags: :x:\n#+identifier: 20261011T120000\n\nBody\n")
147 h.session.open(path)
148 h.answers = ["title": "New Name", "keywords": "b, a"]
149 h.actions.run("app.node.rename")
150 #expect(h.asked.map(\.initial) == ["Old", "x"])
151 let new = h.folder.appendingPathComponent("20261011T120000--new-name__a_b.org").path
152 #expect(h.opened == [new], "\(h.shown)")
153 #expect(try String(contentsOfFile: new, encoding: .utf8) == "#+title: New Name\n#+date: [2026-10-11 Sun 12:00]\n#+filetags: :a:b:\n#+identifier: 20261011T120000\n\nBody\n")
154 }
155
156 @MainActor
157 @Test func renamesFolderFromFrontMatter() throws {
158 let h = try Harness()
159 try h.write("20261011T120000--old__x.org", "#+title: One\n#+filetags: :y:\n")
160 try h.write("20261011T130000--two.org", "#+title: Two\n")
161 try h.write("plain.org", "#+title: Plain\n")
162 h.answers = ["folder": "."]
163 h.actions.run("app.node.rename-folder-from-front-matter")
164 #expect(h.names() == ["20261011T120000--one__y.org", "20261011T130000--two.org", "plain.org"])
165 #expect(h.shown == ["Renamed 1 note"])
166 }
167
168 @MainActor
169 @Test func silos() throws {
170 let h = try Harness()
171 let silo = h.folder.appendingPathComponent("silo").path
172 try FileManager.default.createDirectory(atPath: silo, withIntermediateDirectories: true)
173 let defaults = UserDefaults.standard
174 defaults.set(h.folder.path + ":" + silo, forKey: "denoteSiloDirectories")
175 defer { defaults.removeObject(forKey: "denoteSiloDirectories") }
176 h.answers = ["silo": DenoteNote.abbreviated(silo), "title": "In Silo", "keywords": "k"]
177 h.actions.run("app.node.silo-create")
178 #expect(h.asked.first?.choices == [DenoteNote.abbreviated(h.folder.path), DenoteNote.abbreviated(silo)])
179 #expect(h.opened.count == 1 && h.opened[0].hasPrefix(silo + "/") && h.opened[0].hasSuffix("--in-silo__k.org"))
180 }
181
182 @MainActor
183 @Test func sequenceCommands() throws {
184 let h = try Harness()
185 let root = try h.write("20261001T090000==1--root.org", "#+title: Root\n")
186 let child = try h.write("20261002T090000==1=1--child__k.org", "#+title: Child\n#+filetags: :k:\n#+identifier: 20261002T090000\n#+signature: 1=1\n\nC\n")
187 try h.write("20261003T090000==1=1=1--grandchild.org", "#+title: Grandchild\n")
188 let third = try h.write("20261004T090000==1=3--third.org", "#+title: Third\n")
189 try h.write("20261005T090000==2--two.org", "#+title: Two\n")
190 // A new child of the open note.
191 h.session.open(root)
192 h.answers = ["title": "Kid", "keywords": ""]
193 h.actions.run("app.node.sequence-new-child-of-current")
194 #expect(h.opened.last.map { ($0 as NSString).lastPathComponent }?.hasSuffix("==1=4--kid.org") == true, "\(h.shown)")
195 // The next sibling skips the missing 1=2.
196 h.session.open(child)
197 h.actions.run("app.node.sequence-next-sibling")
198 #expect(h.opened.last == third)
199 // Find: the parent opens at once.
200 h.session.open(child)
201 h.answers = ["relation": "parent"]
202 h.actions.run("app.node.sequence-find")
203 #expect(h.opened.last == root)
204 // Reparenting with descendants under 2.
205 h.session.open(child)
206 h.answers = ["sequence": "20261005T090000==2--two.org"]
207 h.actions.run("app.node.sequence-reparent-recursive")
208 #expect(h.names().contains("20261002T090000==2=1--child__k.org") && h.names().contains("20261003T090000==2=1=1--grandchild.org"), "\(h.names()) \(h.shown)")
209 #expect(try String(contentsOfFile: h.folder.appendingPathComponent("20261002T090000==2=1--child__k.org").path, encoding: .utf8).contains("#+signature: 2=1\n"))
210 // A link to a sequence note says its sequence and title.
211 h.answers = ["sequence": "20261004T090000==1=3--third.org"]
212 h.actions.run("app.node.sequence-link")
213 #expect(h.links.last?.0 == "denote:20261004T090000" && h.links.last?.1 == "1=3 Third")
214 }
215
216 /// `denote-org-capture`: the note's questions first, then the entry filed in it.
217 @MainActor
218 @Test func denoteCapture() throws {
219 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-capture-\(UUID().uuidString)").resolvingSymlinksInPath()
220 defer { try? FileManager.default.removeItem(at: folder) }
221 try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
222 let name = "orgstar-capture-\(UUID().uuidString)"
223 let defaults = UserDefaults(suiteName: name)!
224 defer { defaults.removePersistentDomain(forName: name) }
225 defaults.set("title signature keywords", forKey: "denotePrompts")
226 let capture = DenoteCapture(roots: [folder.path], paths: ["/x/20260101T000000--a__old.org"], defaults: defaults)
227 #expect(capture.questions.map(\.prompt) == ["New file TITLE", "New file SIGNATURE", "New file KEYWORDS"])
228 #expect(capture.questions[2].choices == ["old"])
229 let path = try capture.create(["Captured", "1a", "b a"], now: Self.day)
230 #expect((path as NSString).lastPathComponent == "20261011T120000==1a--captured__a_b.org")
231 let file = folder.appendingPathComponent("capture.toml")
232 try "[[template]]\nkey = \"n\"\nname = \"Note\"\ndenote = true\ntemplate = \"* %?\"\n".write(to: file, atomically: true, encoding: .utf8)
233 let loaded = CaptureTemplates.load(userFile: file)
234 #expect(loaded.problems.isEmpty, "\(loaded.problems)")
235 let template = try #require(loaded.templates.first)
236 #expect(template.options.denote)
237 }
238
92239 /// `denote-prompts` sets the questions after the title and their order.
93240 @MainActor
94241 @Test func denotePromptsInOrder() throws {
@@ -101,7 +248,7 @@ struct DailiesTests {
101248 let actions = RoamActions(session: DocumentSession(recovery: FileRecoveryStore(directory: folder.appendingPathComponent(".r"))),
102249 roots: { [folder.path] }, nodes: { [] }, show: { _ in }, ask: { prompt, reply in asked.append(prompt.key); reply(answers[prompt.key]) },
103250 open: { _, _ in }, insertLink: { _, _ in }, refresh: {})
104 actions.createDenote("Field Notes", root: folder.path, prompts: ["title", "signature", "subdirectory", "date", "file-type", "template", "keywords"],
251 actions.createDenote("Field Notes", roots: [folder.path], prompts: ["title", "signature", "subdirectory", "date", "file-type", "template", "keywords"],
105252 templates: [("report", "* R\n"), ("memo", "* M\n")], keywords: []) { choice in
106253 if case .created(let path, _, _) = choice { created = path }
107254 }
Tests/OrgAppTests/DenoteOracleTests.swift +165 −4
@@ -1,11 +1,13 @@
11import Foundation
22import Testing
33@testable import OrgApp
4import OrgCore
4@testable import OrgCore
55
66/// Denote and denote-journal themselves, run in Emacs, when they're installed: the load-path
77/// directories in `ORGSTAR_DENOTE` (colon-separated), else a Doom or package.el install.
88struct DenoteOracleTests {
9 /// The load-path directories of denote and denote-journal, and of denote-org and
10 /// denote-sequence when they're there too.
911 static let loadPath: [String]? = {
1012 if let paths = ProcessInfo.processInfo.environment["ORGSTAR_DENOTE"] { return paths.split(separator: ":").map(String.init) }
1113 let fm = FileManager.default, home = NSHomeDirectory()
@@ -14,15 +16,17 @@ struct DenoteOracleTests {
1416 } + ["\(home)/.emacs.d/elpa", "\(home)/.config/emacs/elpa"]
1517 for root in roots {
1618 let names = (try? fm.contentsOfDirectory(atPath: root)) ?? []
17 let dirs = ["denote", "denote-journal"].compactMap { package in
19 let dirs = ["denote", "denote-journal", "denote-org", "denote-sequence"].compactMap { package in
1820 names.filter { $0 == package || ($0.hasPrefix(package + "-") && $0.dropFirst(package.count + 1).first?.isNumber == true) }
1921 .sorted().last.map { "\(root)/\($0)" }
2022 }
21 if dirs.count == 2 { return dirs }
23 if dirs.count >= 2, dirs[0].hasSuffix("/denote") || dirs[0].contains("/denote-") { return dirs }
2224 }
2325 return nil
2426 }()
2527
28 static func has(_ package: String) -> Bool { enabled && loadPath!.contains { ($0 as NSString).lastPathComponent == package || ($0 as NSString).lastPathComponent.hasPrefix(package + "-") && ($0 as NSString).lastPathComponent.dropFirst(package.count + 1).first?.isNumber == true } }
29
2630 static var enabled: Bool { loadPath != nil && ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil }
2731
2832 /// Runs `body` with Denote loaded, `denote-directory` at `folder` and nothing backed up.
@@ -111,7 +115,7 @@ struct DenoteOracleTests {
111115 (save-buffer))
112116 """)
113117 let date = try #require(RoamActions.date("2026-10-11 09:30"))
114 _ = try DenoteNote.create(title: "Q4 Plan: draft", keywords: ["work", "ideas"], in: ours.appendingPathComponent("work").path, root: ours.path,
118 _ = try DenoteNote.create(title: "Q4 Plan: draft", keywords: ["work", "ideas"], in: ours.appendingPathComponent("work").path, roots: [ours.path],
115119 now: date, signature: "Part One", template: template)
116120 let names = try FileManager.default.contentsOfDirectory(atPath: theirs.appendingPathComponent("work").path)
117121 #expect(names.count == 1)
@@ -121,4 +125,161 @@ struct DenoteOracleTests {
121125 == String(contentsOf: theirs.appendingPathComponent("work/" + name), encoding: .utf8), "\(name)")
122126 }
123127 }
128
129 /// denote-org's dynamic blocks, each updated in a note by Emacs and by orgstar.
130 @Test(.enabled(if: has("denote-org"))) func blocksMatchDenoteOrg() throws {
131 let dir = try Self.folder()
132 defer { try? FileManager.default.removeItem(at: dir) }
133 try FileManager.default.createDirectory(at: dir.appendingPathComponent("sub"), withIntermediateDirectories: true)
134 let notes = [
135 "20261001T090000--alpha-note__emacs_work.org": "#+title: Alpha Note\n#+filetags: :emacs:work:\n#+identifier: 20261001T090000\n\n* First\nSee [[denote:20261119T120000][Current]].\n** Deeper\n#+begin_src sh\necho\n#+end_src\n",
136 "20261002T090000==1a--beta__emacs.org": "#+title: Beta\n#+filetags: :emacs:\n#+identifier: 20261002T090000\n\nBeta body.\n",
137 "sub/20260930T090000--gamma-in-sub__work.org": "#+title: Gamma in Sub\n#+filetags: :work:\n#+identifier: 20260930T090000\n\nGamma links [[denote:20261119T120000::#top][here]].\n",
138 "20261003T090000--delta__misc.md": "---\ntitle: Delta\n---\n\nDelta.\n",
139 "plain.org": "* Not a note\n",
140 "20261004T090000==1--root__seq.org": "#+title: Root\n\nR\n",
141 "20261005T090000==1=1--first__seq.org": "#+title: First\n\nF\n",
142 "20261006T090000==1=2--second__seq.org": "#+title: Second\n\nS\n",
143 "20261007T090000==1=1=1--deep__seq.org": "#+title: Deep\n\nD\n",
144 "20261008T090000==2--other__seq.org": "#+title: Other\n\nO\n",
145 ]
146 for (name, text) in notes { try text.write(to: dir.appendingPathComponent(name), atomically: true, encoding: .utf8) }
147 let current = dir.appendingPathComponent("20261119T120000--current.org")
148 let head = "#+title: Current\n#+identifier: 20261119T120000\n\nAlready: [[denote:20261002T090000][Beta]]\n\n"
149 let blocks = [
150 "denote-links :regexp \"_emacs\"",
151 "denote-links :regexp \".\" :sort-by-component title :reverse-sort t",
152 "denote-links :regexp \"_work\" :id-only t",
153 "denote-links :regexp \"_work\" :include-date t :block-name \"mine\"",
154 "denote-links :regexp \".\" :not-regexp \"sub\" :sort-by-component signature",
155 "denote-missing-links :regexp \".\"",
156 "denote-backlinks",
157 "denote-files :regexp \"beta\"",
158 "denote-files :regexp \"_work\" :no-front-matter t :add-links t :file-separator t",
159 "denote-files :regexp \"_work\" :no-front-matter 2",
160 "denote-files-as-headings :regexp \"_work\"",
161 "denote-files-as-headings :regexp \"_work\" :add-links t :exclude-tags t",
162 "denote-sequence :sequence \"1\" :depth 2",
163 "denote-sequence :sequence \"1=1\"",
164 "denote-sequence :sequence \"\"",
165 ]
166 let paths = Self.loadPath!.map(\.debugDescription).joined(separator: " ")
167 for block in blocks {
168 let text = head + "#+BEGIN: \(block)\nold\n#+END:\n"
169 try text.write(to: current, atomically: true, encoding: .utf8)
170 let theirs = try DailiesTests.emacs("""
171 (progn (setq load-path (append (list \(paths)) load-path) coding-system-for-read 'utf-8 coding-system-for-write 'utf-8)
172 (require 'org) (require 'denote) (require 'denote-sequence nil t) (require 'denote-org)
173 (setq denote-directory \((dir.path + "/").debugDescription))
174 (find-file \(current.path.debugDescription))
175 (goto-char (point-min)) (re-search-forward "^#\\\\+BEGIN:") (beginning-of-line)
176 (org-update-dblock)
177 (princ (buffer-string)))
178 """)
179 var options = EditingOptions.org
180 options.filePath = current.path
181 options.denoteDirectories = [dir.path]
182 let begin = (text as NSString).range(of: "#+BEGIN:").location
183 let context = EditContext(revision: 0, text: text, tree: OrgParser.parse(text), selection: [begin..<begin], options: options)
184 var ours = text
185 if case .commit(let result) = UpdateDynamicBlock().run(in: context) {
186 for edit in result.edits.sorted(by: { $0.range.lowerBound > $1.range.lowerBound }) { ours = edit.apply(to: ours) }
187 } else {
188 ours = "failed"
189 }
190 #expect(ours == theirs, "\(block)\nours:\n\(ours)\ntheirs:\n\(theirs)")
191 }
192 }
193
194 /// denote-sequence's new parents, children and siblings, relatives and conversions, for
195 /// notes in each scheme, from Emacs and from orgstar.
196 @Test(.enabled(if: has("denote-sequence"))) func sequencesMatchDenoteSequence() throws {
197 let sets: [(DenoteSequence.Scheme, [String])] = [
198 (.numeric, ["1", "1=1", "1=2", "1=1=1", "1=1=1=1", "2", "3=1", "10", "10=9", "10=10", "2=1=5"]),
199 (.alphanumeric, ["1", "1a", "1b", "1a1", "1a2", "1z", "2", "2a1a", "3", "1za"]),
200 (.alphanumericDelimited, ["1", "1=a", "1=b", "1=a1b", "1=a1b=1", "2", "2=a", "1=a2"]),
201 ]
202 let paths = Self.loadPath!.map(\.debugDescription).joined(separator: " ")
203 for (scheme, sequences) in sets {
204 let dir = try Self.folder()
205 defer { try? FileManager.default.removeItem(at: dir) }
206 for (index, sequence) in sequences.enumerated() {
207 try "x\n".write(to: dir.appendingPathComponent(String(format: "20260101T%06d==%@--n%d.org", index, sequence, index)), atomically: true, encoding: .utf8)
208 }
209 let names = sequences.map(\.debugDescription).joined(separator: " ")
210 let relations = DenoteSequence.Relation.allCases.map(\.rawValue).joined(separator: " ")
211 let theirs = try DailiesTests.emacs("""
212 (progn (setq load-path (append (list \(paths)) load-path))
213 (require 'denote) (require 'denote-sequence)
214 (setq denote-directory \((dir.path + "/").debugDescription) denote-sequence-scheme '\(scheme.rawValue))
215 (defmacro try (form) `(condition-case nil ,form (error "ERR")))
216 (princ (format "parent %s\\n" (try (denote-sequence-get-new 'parent))))
217 (dolist (s (list \(names)))
218 (princ (format "child %s %s\\n" s (try (denote-sequence-get-new 'child s))))
219 (princ (format "sibling %s %s\\n" s (try (denote-sequence-get-new 'sibling s))))
220 (dolist (target '(numeric alphanumeric alphanumeric-delimited))
221 (princ (format "convert %s %s %s\\n" s target (try (denote-sequence-make-conversion s target)))))
222 (dolist (relation '(\(relations)))
223 (princ (format "%s %s %s\\n" relation s
224 (try (let ((found (denote-sequence-get-relative s relation)))
225 (string-join (sort (mapcar #'file-name-nondirectory (if (stringp found) (list found) found)) #'string<) ","))))))))
226 """)
227 let model = DenoteSequence(scheme: scheme)
228 let files = DenoteSequence.files(DenoteBlocks.files(in: [dir.path]).map(\.path))
229 let all = files.map(\.sequence)
230 func attempt(_ body: () throws -> String) -> String { (try? body()) ?? "ERR" }
231 var ours = "parent \(attempt { try model.newParent(among: all) })\n"
232 for s in sequences {
233 ours += "child \(s) \(attempt { try model.newChild(of: s, among: all) })\n"
234 ours += "sibling \(s) \(attempt { try model.newSibling(of: s, among: all) })\n"
235 for target in DenoteSequence.Scheme.allCases {
236 ours += "convert \(s) \(target.rawValue) \(attempt { try model.converted(s, to: target) })\n"
237 }
238 for relation in DenoteSequence.Relation.allCases {
239 ours += "\(relation.rawValue) \(s) \(attempt { try model.relatives(of: s, relation, in: files).map { ($0 as NSString).lastPathComponent }.sorted().joined(separator: ",") })\n"
240 }
241 }
242 let theirLines = theirs.split(separator: "\n").map(String.init), ourLines = ours.split(separator: "\n").map(String.init)
243 #expect(theirLines.count == ourLines.count, "\(scheme)\n\(theirs)")
244 for (a, b) in zip(ourLines, theirLines) where a != b {
245 Issue.record("\(scheme): ours \(a) | theirs \(b)")
246 }
247 }
248 }
249
250 /// `denote-rename-file` with a new title, keywords, signature and date: on a note, on one
251 /// whose signature goes, and on a file without front matter or identifier.
252 @Test(.enabled(if: enabled)) func renamesMatchDenote() throws {
253 let theirs = try Self.folder(), ours = try Self.folder()
254 defer { try? FileManager.default.removeItem(at: theirs); try? FileManager.default.removeItem(at: ours) }
255 let files = [
256 "20261011T120000--old-title__x.org": "#+title: Old Title\n#+date: [2026-10-11 Sun 12:00]\n#+filetags: :x:\n#+identifier: 20261011T120000\n#+startup: overview\n\nBody\n",
257 "20261011T130000==zz--has-sig.org": "#+title: Has Sig\n#+date: [2026-10-11 Sun 12:00]\n#+filetags: \n#+identifier: 20261011T130000\n#+signature: zz\n\nBody\n",
258 "plain.org": "* Heading\nNo front matter\n",
259 ]
260 for dir in [theirs, ours] { for (name, text) in files { try text.write(to: dir.appendingPathComponent(name), atomically: true, encoding: .utf8) } }
261 let renames: [(file: String, title: String, keywords: [String], signature: String)] = [
262 ("20261011T120000--old-title__x.org", "New Title", ["zeta", "Alpha"], "Part One"),
263 ("20261011T130000==zz--has-sig.org", "Has Sig", [], ""),
264 ("plain.org", "Plain Note", ["k"], ""),
265 ]
266 let calls = renames.map { r in
267 "(denote-rename-file \(theirs.appendingPathComponent(r.file).path.debugDescription) \(r.title.debugDescription) (list \(r.keywords.map(\.debugDescription).joined(separator: " "))) \(r.signature.debugDescription) \"2026-10-11 12:00:00\" \((Denote.identifier(ofFile: r.file) ?? "").debugDescription))"
268 }.joined(separator: "\n")
269 try Self.denote(theirs, calls + "\n(save-some-buffers t)")
270 let date = Calendar.current.date(from: DateComponents(year: 2026, month: 10, day: 11, hour: 12))!
271 for r in renames {
272 let path = ours.appendingPathComponent(r.file).path
273 let text = try String(contentsOfFile: path, encoding: .utf8)
274 let (target, rewritten) = DenoteNote.renaming(path, text: text, title: r.title, keywords: r.keywords, signature: r.signature, date: date, roots: [ours.path])
275 try rewritten.write(toFile: path, atomically: true, encoding: .utf8)
276 if target != path { try FileManager.default.moveItem(atPath: path, toPath: target) }
277 }
278 let names = try FileManager.default.contentsOfDirectory(atPath: theirs.path).sorted()
279 #expect(try FileManager.default.contentsOfDirectory(atPath: ours.path).sorted() == names)
280 for name in names {
281 #expect(try String(contentsOf: ours.appendingPathComponent(name), encoding: .utf8)
282 == String(contentsOf: theirs.appendingPathComponent(name), encoding: .utf8), "\(name)")
283 }
284 }
124285}
Tests/OrgAppTests/EmacsImportTests.swift +2
@@ -272,12 +272,14 @@ struct EmacsImportTests {
272272 (setq denote-directory "~/notes/")
273273 (setq denote-journal-directory "~/notes/journal/" denote-journal-keyword "diary")
274274 (setq denote-journal-title-format 'day-date-month-year-24h)
275 (setq denote-journal-interval 'weekly)
275276 """#.write(to: folder.appendingPathComponent("init.el"), atomically: true, encoding: .utf8)
276277 let s = settings(EmacsImport.scan(EmacsImport.files(in: folder)))
277278 #expect(s["denote-directory"] == .string("~/notes/"))
278279 #expect(s["denote-journal-directory"] == .string("~/notes/journal/"))
279280 #expect(s["denote-journal-keyword"] == .string("diary"))
280281 #expect(s["denote-journal-title-format"] == .string("%A %-e %B %Y %H:%M"))
282 #expect(s["denote-journal-interval"] == .string("weekly"))
281283 }
282284
283285 @MainActor
Tests/OrgCoreTests/LinkStoreTests.swift +18
@@ -231,3 +231,21 @@ struct LinkStoreTests {
231231 #expect(links == [a, b])
232232 }
233233}
234
235struct DenoteStoreLinkTests {
236 func context(_ text: String, caret: Int) -> EditContext {
237 EditContext(revision: 0, text: text, tree: OrgParser.parse(text), selection: [caret..<caret])
238 }
239
240 /// `denote-link-ol-store`: the note's identifier, with a CUSTOM_ID when the entry has one.
241 @Test func storesDenoteLinks() {
242 let text = "#+title: A Note\n\n* Plain\nx\n* Custom\n:PROPERTIES:\n:CUSTOM_ID: here\n:END:\ny\n"
243 let path = "/n/20261119T120000==1a--a-note__kw.org"
244 #expect(Links.storeDenote(in: context(text, caret: 0), path: path) == StoredLink(link: "denote:20261119T120000", description: "A Note"))
245 #expect(Links.storeDenote(in: context(text, caret: (text as NSString).range(of: "x\n").location), path: path)?.link == "denote:20261119T120000")
246 #expect(Links.storeDenote(in: context(text, caret: (text as NSString).range(of: "y\n").location), path: path)?.link == "denote:20261119T120000::#here")
247 #expect(Links.storeDenote(in: context("* x\n", caret: 0), path: "/n/20261119T120000--from-name.org")?.description == "from name")
248 #expect(Links.storeDenote(in: context(text, caret: 0), path: "/n/plain.org") == nil)
249 }
250}
251
docs/manual/guide/03-keys.org +18
@@ -1071,6 +1071,24 @@ See [[file:09-links.org][Links]].
10711071| Next Daily Note (=app.dailies.next=) | =C-c n d f= | — | =SPC n r d f= (N) | =org-roam-dailies-goto-next-note=. |
10721072| Previous Daily Note (=app.dailies.previous=) | =C-c n d b= | — | =SPC n r d b= (N) | =org-roam-dailies-goto-previous-note=. |
10731073| Rename Note from Front Matter (=app.node.rename-from-front-matter=) | — | — | — | =denote-rename-file-using-front-matter=. |
1074| Rename Note… (=app.node.rename=) | — | — | — | =denote-rename-file=. |
1075| Rename Notes in Folder from Front Matter… (=app.node.rename-folder-from-front-matter=) | — | — | — | =denote-dired-rename-marked-files-using-front-matter=. |
1076| Find Note in Silo… (=app.node.silo-find=) | — | — | — | =denote-silo-open-or-create=. |
1077| New Note in Silo… (=app.node.silo-create=) | — | — | — | =denote-silo-create-note=. |
1078| New Sequence Note… (=app.node.sequence-new-parent=) | — | — | — | =denote-sequence-new-parent=. |
1079| New Child Sequence Note… (=app.node.sequence-new-child=) | — | — | — | =denote-sequence-new-child=. |
1080| New Sibling Sequence Note… (=app.node.sequence-new-sibling=) | — | — | — | =denote-sequence-new-sibling=. |
1081| New Child of This Note… (=app.node.sequence-new-child-of-current=) | — | — | — | =denote-sequence-new-child-of-current=. |
1082| New Sibling of This Note… (=app.node.sequence-new-sibling-of-current=) | — | — | — | =denote-sequence-new-sibling-of-current=. |
1083| Find Sequence Relatives… (=app.node.sequence-find=) | — | — | — | =denote-sequence-find=. |
1084| Next Sibling Note (=app.node.sequence-next-sibling=) | — | — | — | =denote-sequence-find-next-sibling=. |
1085| Previous Sibling Note (=app.node.sequence-previous-sibling=) | — | — | — | =denote-sequence-find-previous-sibling=. |
1086| Reparent Note… (=app.node.sequence-reparent=) | — | — | — | =denote-sequence-reparent=. |
1087| Reparent Note with Descendants… (=app.node.sequence-reparent-recursive=) | — | — | — | =denote-sequence-reparent-recursive=. |
1088| Rename Note as Sequence Parent (=app.node.sequence-rename-as-parent=) | — | — | — | =denote-sequence-rename-as-parent=. |
1089| Convert Note Sequence Scheme (=app.node.sequence-convert=) | — | — | — | =denote-sequence-convert=. |
1090| Insert Sequence Link… (=app.node.sequence-link=) | — | — | — | =denote-sequence-link=. |
1091| Sequence Hierarchy… (=app.node.sequence-hierarchy=) | — | — | — | =denote-sequence-view-hierarchy=. |
10741092
10751093** Unbound commands
10761094
docs/manual/guide/08-capture.org +2 −1
@@ -112,7 +112,7 @@ The first list then shows =[w] Work…= in place of the templates under it; choo
112112| =name= | string | The name in the list; the key when omitted | description |
113113| =type= | string | =entry= (the default), =item=, =checkitem=, =plain= or =table-line= | type |
114114| =template= | string, required | The text to fill; see [[*Template escapes][Template escapes]] | template |
115| =file= | string | The target file; required except with =id= or =clock= | target |
115| =file= | string | The target file; required except with =id=, =clock= or =denote= | target |
116116| =headline= | string | A heading in =file= | =file+headline= |
117117| =olp= | string | An outline path in =file=, titles separated by =/= | =file+olp= |
118118| =datetree= | boolean | Today's entry in a date tree in =file=, under =olp= if given | =file+olp+datetree= |
@@ -121,6 +121,7 @@ The first list then shows =[w] Work…= in place of the templates under it; choo
121121| =regexp= | string | After the first match of an Emacs regexp in =file= | =file+regexp= |
122122| =id= | string | The heading with this =ID= property, in any file | =id= |
123123| =clock= | boolean | The entry the clock is running in | =clock= |
124| =denote= | boolean | A new Denote note, asked for first; see [[file:09-links.org::*Capture][Denote capture]] | =denote-org-capture= |
124125| =prepend= | boolean | Put the text first rather than last | =:prepend= |
125126| =immediate-finish= | boolean | File without showing the editor | =:immediate-finish= |
126127| =empty-lines= | integer | Blank lines before and after the captured text | =:empty-lines= |
docs/manual/guide/09-links.org +109 −7
@@ -369,20 +369,122 @@ With =notes-package = "denote"= in =config.toml=, the same commands follow Denot
369369 punctuation, words joined by =-=; the keywords sorted, each one word, joined by =_=.
370370- The daily-note commands work on denote-journal's entries: notes in
371371 =denote-journal-directory= (=journal=, under =denote-directory=) with the
372 =denote-journal-keyword= (=journal=). A day's entry is the one whose identifier has its
373 date; a new one is titled by =denote-journal-title-format= (="%A %-e %B %Y %H:%M"=). Capturing
372 =denote-journal-keyword= (=journal=). With =denote-journal-interval= (=daily=), one entry
373 lasts a day, a week (Monday to Sunday), a month or a year, and the entry for a date is
374 the one whose identifier's date is in that stretch. denote-journal itself takes a date
375 outside the current week, month or year as today; orgstar uses the date's own. A new
376 entry is titled by =denote-journal-title-format= (="%A %-e %B %Y %H:%M"=). Capturing
374377 adds =org-roam-dailies-entry= as for org-roam.
378- Store Link in a Denote note stores =[[denote:ID][Title]]=, or =denote:ID::#custom-id=
379 in an entry with a =CUSTOM_ID=, as Denote does with =denote-org-store-link-to-heading=
380 nil.
381
382=denote-directory= can hold several folders, separated by =:=. New notes go in the first;
383the =subdirectory= question offers all of them and their folders, and identifiers are
384kept unique across them.
385
386*** Renaming
387
388- Rename Note… (=denote-rename-file=) asks the questions =denote-prompts= has among
389 =title=, =keywords=, =signature= and =date=, each starting with the current value, then
390 renames the file in its folder and rewrites its front matter. Empty answers remove a
391 part. A file without an identifier gets one from its modification time; a file
392 without front matter gets it added at the top.
375393- Rename Note from Front Matter renames the open file from its =#+title:=,
376394 =#+filetags:= and =#+signature:=, keeping its identifier, as
377395 =denote-rename-file-using-front-matter= does. A missing line leaves that part out of
378 the name, and the keywords keep their order. Links keep working, as they use the
379 identifier.
396 the name, and the keywords keep their order.
397- Rename Notes in Folder from Front Matter… does that for every Denote note in a
398 folder of =denote-directory=, as =denote-dired-rename-marked-files-using-front-matter=
399 does with them all marked.
400
401Links keep working after a rename, as they use the identifier.
402
403*** Query links
404
405=[[denote:query-contents:REGEXP]]= and =[[denote:query-filenames:REGEXP]]= offer the
406notes whose text, or name, the Emacs regexp matches, ignoring case, and open the one
407chosen. In the iOS reader they list the matches.
408
409*** Silos
410
411New Note in Silo… and Find Note in Silo… (denote-silo) ask for a folder of
412=denote-silo-directories= (=denote-directory='s folders unless set, separated by =:=)
413and work as if it were =denote-directory=. Find Note in Silo… lists the notes in the
414sidebar folders that are under it.
380415
381Import from Emacs reads =denote-directory=, =denote-prompts=, =denote-templates=,
382=denote-journal-directory=, =denote-journal-keyword= and =denote-journal-title-format=.
383Templates that are functions, and Denote notes in Markdown or plain text, are not
416*** Capture
417
418A capture template with =denote = true= and no =file= puts its entry in a new note, as
419=denote-org-capture= does: it asks for the title and the =denote-prompts= questions before
420its own. See [[file:08-capture.org][Capture]].
421
422#+BEGIN_SRC toml
423[[template]]
424key = "n"
425name = "New note"
426denote = true
427type = "plain"
428template = "%i\n%?"
429#+END_SRC
430
431*** Dynamic blocks
432
433denote-org's dynamic blocks update with =C-c C-c= on their =#+BEGIN:= line or Update
434Dynamic Block, over the files in =denote-directory=:
435
436| Block | What it lists |
437|-------+---------------|
438| =denote-links= | Links to the notes whose names (relative to =denote-directory=) match =:regexp= |
439| =denote-missing-links= | The same, without the notes this file links to already |
440| =denote-backlinks= | Links to the notes that link to this one |
441| =denote-files= | The text of the notes matching =:regexp= |
442| =denote-files-as-headings= | The same, each note's title a heading and its headings one level down |
443| =denote-sequence= | A note's descendants, =:depth= levels deep, indented; with =:sequence ""= every note with a sequence |
444
445They take denote-org's parameters: =:not-regexp=, =:sort-by-component= (=title=,
446=keywords=, =signature=, =identifier=, =last-modified=, =random=), =:reverse-sort=,
447=:id-only=, =:include-date=, =:block-name=, and for =denote-files= =:no-front-matter=,
448=:add-links= and =:file-separator=, for =denote-files-as-headings= =:add-links= and
449=:exclude-tags=. =:excluded-dirs-regexp=, =:this-heading-only= and =rx= forms aren't
384450supported.
385451
452#+BEGIN_SRC org
453,#+BEGIN: denote-links :regexp "_emacs" :sort-by-component title
454,#+END:
455#+END_SRC
456
457*** Sequences
458
459denote-sequence numbers notes in a hierarchy through their signatures, in the scheme
460=denote-sequence-scheme= sets: =numeric= (~1~, ~1=1~, ~1=1=2~), =alphanumeric= (~1~,
461~1a~, ~1a2~) or =alphanumeric-delimited= (~1~, ~1=a~, ~1=a2~). New sequences come out
462as denote-sequence 0.3 gives them.
463
464| Command | denote-sequence |
465|---------+-----------------|
466| New Sequence Note… | =denote-sequence-new-parent= |
467| New Child Sequence Note…, New Sibling Sequence Note… | =denote-sequence-new-child=, =-new-sibling= |
468| New Child of This Note…, New Sibling of This Note… | =denote-sequence-new-child-of-current=, =-new-sibling-of-current= |
469| Find Sequence Relatives… | =denote-sequence-find=: all parents, the parent, siblings, children or all children |
470| Next Sibling Note, Previous Sibling Note | =denote-sequence-find-next-sibling=, =-previous-sibling= |
471| Reparent Note…, Reparent Note with Descendants… | =denote-sequence-reparent=, =-reparent-recursive= |
472| Rename Note as Sequence Parent | =denote-sequence-rename-as-parent= |
473| Convert Note Sequence Scheme | =denote-sequence-convert= to =denote-sequence-scheme= |
474| Insert Sequence Link… | =denote-sequence-link= |
475| Sequence Hierarchy… | =denote-sequence-view-hierarchy=, as a list to open a note from |
476
477A new sequence note asks for its title and the =denote-prompts= questions other than
478=signature=, which is the sequence.
479
480*** Importing and limits
481
482Import from Emacs reads =denote-directory= (a folder or a list), =denote-prompts=,
483=denote-templates=, =denote-silo-directories=, =denote-sequence-scheme=,
484=denote-journal-directory=, =denote-journal-keyword=, =denote-journal-interval= and
485=denote-journal-title-format=. Templates that are functions, and Denote notes in
486Markdown or plain text, are not supported.
487
386488* Inline images
387489
388490=org-toggle-inline-images= shows image links as images.
docs/manual/guide/13-configuration.org +7 −2
@@ -179,7 +179,7 @@ These settings have no control in the Settings window. Some are in the View menu
179179| =org-track-ordered-property-with-tag= | |
180180| =org-timer-format=, =org-timer-default-timer= | |
181181| =org-roam-directory=, =org-roam-dailies-directory=, =org-roam-dailies-file=, =org-roam-dailies-head=, =org-roam-dailies-entry= | |
182| =notes-package=, =denote-directory=, =denote-prompts=, =denote-journal-directory=, =denote-journal-keyword=, =denote-journal-title-format= | |
182| =notes-package=, =denote-directory=, =denote-prompts=, =denote-silo-directories=, =denote-sequence-scheme=, =denote-journal-directory=, =denote-journal-keyword=, =denote-journal-interval=, =denote-journal-title-format= | |
183183| =org-attach-id-dir=, =org-attach-use-inheritance= | |
184184| =org-yank-image-save-method=, =org-yank-dnd-method= | |
185185| =org-crypt-tag-matcher= | |
@@ -240,10 +240,13 @@ A key you remove from the file goes back to its default. A key that isn't in the
240240| =org-roam-dailies-head= | string | ="#+title: %<%Y-%m-%d>\n"= | What a new daily note starts with, under its =ID=. |
241241| =org-roam-dailies-entry= | string | ="* %?"= | The capture template Capture to Daily Note files. See [[file:09-links.org][Links]]. |
242242| =notes-package= | string | ="org-roam"= | Whose conventions Find Node…, Insert Node Link… and the daily-note commands follow: ="org-roam"= or ="denote"=. |
243| =denote-directory= | string | =""= | The folder new Denote notes go in; empty for the first sidebar folder. Mirrors =denote-directory=. |
243| =denote-directory= | string | =""= | The folders of Denote notes, separated by =:=, new notes going in the first; empty for the first sidebar folder. Mirrors =denote-directory=. |
244| =denote-silo-directories= | string | =""= | The folders New Note in Silo… and Find Note in Silo… choose from, separated by =:=; empty for =denote-directory='s. Mirrors =denote-silo-directories=. |
245| =denote-sequence-scheme= | string | ="numeric"= | How denote-sequence numbers notes: ="numeric"=, ="alphanumeric"= or ="alphanumeric-delimited"=. Mirrors =denote-sequence-scheme=. |
244246| =denote-prompts= | string | ="title keywords"= | What a new Denote note asks, in order, separated by spaces: =title=, =keywords=, =subdirectory=, =date=, =template=, =signature=. Mirrors =denote-prompts=. |
245247| =denote-journal-directory= | string | ="journal"= | The folder journal entries are in, relative to =denote-directory=. Mirrors =denote-journal-directory=. |
246248| =denote-journal-keyword= | string | ="journal"= | The keyword journal entries have. Mirrors =denote-journal-keyword=. |
249| =denote-journal-interval= | string | ="daily"= | How long one journal entry lasts: ="daily"=, ="weekly"=, ="monthly"= or ="yearly"=. Mirrors =denote-journal-interval=. |
247250| =denote-journal-title-format= | string | ="%A %-e %B %Y %H:%M"= | A new journal entry's title, a =format-time-string= format. |
248251| =org-timer-format= | string | ="%s "= | What Insert Timer Value writes, with =%s= for the =h:mm:ss= value. Mirrors =org-timer-format=. |
249252| =org-timer-default-timer= | string | ="0"= | The countdown Set Countdown Timer… offers, in minutes or =h:mm:ss=; ="0"= offers none. Mirrors =org-timer-default-timer=. |
@@ -638,6 +641,8 @@ Only variables whose names start with =org-=, =appt-=, =display-line-numbers=, =
638641| =org-roam-directory=, =org-roam-dailies-directory= | The same keys, when the value is a string or a form that makes one |
639642| =denote-directory=, =denote-journal-directory=, =denote-journal-keyword= | The same keys, when the value is a string |
640643| =denote-prompts= | The same key, the symbols separated by spaces |
644| =denote-directory= as a list, =denote-silo-directories= | The same key, the folders separated by =:= |
645| =denote-sequence-scheme=, =denote-journal-interval= | The same key |
641646| =denote-templates= | =[denote-templates]=: entries whose text is a string or =concat= of strings; a function is listed as unsupported |
642647| =denote-journal-title-format= | The same key; the symbols =day-date-month-year=, =-24h= and =-12h= become their formats |
643648| =org-roam-dailies-capture-templates= | =org-roam-dailies-file=, =-head= and =-entry=, from the first template's =(file+head NAME HEAD)= target and template |
docs/manual/guide/15-alongside-emacs.org +1 −1
@@ -235,7 +235,7 @@ Tables and dynamic blocks (see [[file:10-tables.org][Tables]] and [[file:06-date
235235
236236- Formulas outside orgstar's own calculator go to Emacs on the Mac and are refused on iOS.
237237- Clock tables support the scopes =nil=, =file=, =subtree= and =treeN=; other scopes, =:match= and =:step= aren't supported.
238- Dynamic blocks other than =clocktable= and =columnview= aren't supported. Column views of other files aren't supported.
238- Dynamic blocks other than =clocktable=, =columnview= and denote-org's aren't supported. Column views of other files aren't supported.
239239
240240Other:
241241