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

merged merged by cmc on 2026-11-19 21:02 UTC · krz/orgstar:denote-more into main

35 files changed, +1792 −76

Layout: unified · split

Sources/OrgApp/CaptureModel.swift +2 −2
@@ -56,7 +56,7 @@ public enum CaptureTemplates {
56 groups.append(CaptureGroup(key: key, name: name)) 56 groups.append(CaptureGroup(key: key, name: name))
57 continue 57 continue
58 } 58 }
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
60 guard let key = values["key"]?.string, let body = values["template"]?.string, let file = values["file"]?.string ?? (fileless ? "" : nil) else { 60 guard let key = values["key"]?.string, let body = values["template"]?.string, let file = values["file"]?.string ?? (fileless ? "" : nil) else {
61 problems.append("capture.toml line \(table.line): a template needs key, file and template") 61 problems.append("capture.toml line \(table.line): a template needs key, file and template")
62 continue 62 continue
@@ -92,7 +92,7 @@ public enum CaptureTemplates {
92 prepend: flag("prepend"), immediateFinish: flag("immediate-finish"), emptyLines: lines("empty-lines"), 92 prepend: flag("prepend"), immediateFinish: flag("immediate-finish"), emptyLines: lines("empty-lines"),
93 emptyLinesBefore: lines("empty-lines-before"), emptyLinesAfter: lines("empty-lines-after"), 93 emptyLinesBefore: lines("empty-lines-before"), emptyLinesAfter: lines("empty-lines-after"),
94 jumpToCaptured: flag("jump-to-captured"), clockIn: flag("clock-in"), clockKeep: flag("clock-keep"), clockResume: flag("clock-resume"), 94 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")
96 ) 96 )
97 templates.append(CaptureTemplate(key: key, name: values["name"]?.string ?? key, kind: kind, target: target, template: body, options: options)) 97 templates.append(CaptureTemplate(key: key, name: values["name"]?.string ?? key, kind: kind, target: target, template: body, options: options))
98 } 98 }
Sources/OrgApp/Dailies.swift +25 −4
@@ -27,10 +27,31 @@ public struct Dailies: Sendable, Equatable {
27 public var keyword: String 27 public var keyword: String
28 /// `denote-journal-title-format`, a `format-time-string` format. 28 /// `denote-journal-title-format`, a `format-time-string` format.
29 public var title: String 29 public var title: String
30 /// `denote-journal-interval`: `daily`, `weekly`, `monthly` or `yearly`, how long one
31 /// entry lasts.
32 public var interval: String
30 33
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") {
32 self.keyword = keyword 35 self.keyword = keyword
33 self.title = title 36 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 }
34 } 55 }
35 } 56 }
36 57
@@ -48,7 +69,8 @@ public struct Dailies: Sendable, Equatable {
48 if OrgPreferences.usesDenote(defaults) { 69 if OrgPreferences.usesDenote(defaults) {
49 guard let base = DenoteNote.directory(roots: roots, defaults: defaults) else { return nil } 70 guard let base = DenoteNote.directory(roots: roots, defaults: defaults) else { return nil }
50 return Dailies(directory: OrgAttach.expand(OrgPreferences.denoteJournalDirectory(defaults), in: base), entry: OrgPreferences.dailiesEntry(defaults), 71 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)))
52 } 74 }
53 let roam = OrgPreferences.roamDirectory(defaults) 75 let roam = OrgPreferences.roamDirectory(defaults)
54 guard let base = roam.isEmpty ? roots.first : OrgAttach.expand(roam, in: roots.first ?? NSHomeDirectory()) else { return nil } 76 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 {
72 94
73 public func path(for day: Date) -> String { 95 public func path(for day: Date) -> String {
74 if let journal { 96 if let journal {
75 let date = Denote.identifier(for: day).prefix(8) 97 if let found = files().first(where: { Denote.identifier(ofFile: $0).map { journal.covers($0, day) } == true }) { return found }
76 if let found = files().first(where: { Denote.identifier(ofFile: $0)?.hasPrefix(date) == true }) { return found }
77 let name = Denote.fileName(identifier: Denote.identifier(for: day), title: Self.strftime(journal.title, day), keywords: [journal.keyword]) 98 let name = Denote.fileName(identifier: Denote.identifier(for: day), title: Self.strftime(journal.title, day), keywords: [journal.keyword])
78 return (directory as NSString).appendingPathComponent(name) 99 return (directory as NSString).appendingPathComponent(name)
79 } 100 }
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
5/// `denote-directory` or a folder under it, starting with the Org front matter and then the 5/// `denote-directory` or a folder under it, starting with the Org front matter and then the
6/// template. 6/// template.
7public enum DenoteNote { 7public 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`.
9 public static func directory(roots: [String], defaults: UserDefaults = .standard) -> String? { 16 public static func directory(roots: [String], defaults: UserDefaults = .standard) -> String? {
10 let denote = OrgPreferences.denoteDirectory(defaults) 17 directories(roots: roots, defaults: defaults).first
11 return denote.isEmpty ? roots.first : OrgAttach.expand(denote, in: roots.first ?? NSHomeDirectory()) 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) }
12 } 46 }
13 47
14 /// `denote-directory-subdirectories`: the folders under `root`, relative to it, without 48 /// `denote-directory-subdirectories`: the folders under `root`, relative to it, without
@@ -31,16 +65,40 @@ public enum DenoteNote {
31 return found 65 return found
32 } 66 }
33 67
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
34 /// Makes the note's file in `folder`. Its identifier is `now`'s, or as 94 /// Makes the note's file in `folder`. Its identifier is `now`'s, or as
35 /// `denote-generate-identifier-as-date` does, the first second after it no file under 95 /// `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.
37 public static func create( 98 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 = ""
39 ) throws -> (path: String, id: String) { 100 ) throws -> (path: String, id: String) {
40 let used = identifiers(under: root ?? folder) 101 let id = unusedIdentifier(now, roots: roots.isEmpty ? [folder] : roots)
41 var stamp = now
42 while used.contains(Denote.identifier(for: stamp)) { stamp += 1 }
43 let id = Denote.identifier(for: stamp)
44 let keywords = Denote.keywords(keywords) 102 let keywords = Denote.keywords(keywords)
45 let signature = Denote.signature(signature) 103 let signature = Denote.signature(signature)
46 let name = Denote.fileName(identifier: id, signature: signature, title: title, keywords: keywords) 104 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 {
559 add(name, .string(format)) 559 add(name, .string(format))
560 case "org-timer-default-timer": 560 case "org-timer-default-timer":
561 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") } 561 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: ":")))
562 case "denote-directory", "denote-journal-directory", "denote-journal-keyword": 567 case "denote-directory", "denote-journal-directory", "denote-journal-keyword":
563 guard let text = value.string else { return note("not a string") } 568 guard let text = value.string else { return note("not a string") }
564 add(name, .string(text)) 569 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))
565 case "denote-journal-title-format": 576 case "denote-journal-title-format":
566 let formats = ["day-date-month-year": "%A %-e %B %Y", "day-date-month-year-24h": "%A %-e %B %Y %H:%M", 577 let formats = ["day-date-month-year": "%A %-e %B %Y", "day-date-month-year-24h": "%A %-e %B %Y %H:%M",
567 "day-date-month-year-12h": "%A %-e %B %Y %I:%M %p", "day": "%A"] 578 "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 {
8 /// For the system to open: a web or mail address, or a file Orgstar doesn't edit. 8 /// For the system to open: a web or mail address, or a file Orgstar doesn't edit.
9 case openExternally(URL) 9 case openExternally(URL)
10 case message(String) 10 case message(String)
11 /// Files to choose one of to open: a Denote query link's matches.
12 case choose(prompt: String, paths: [String])
11} 13}
12 14
13extension DocumentSession { 15extension DocumentSession {
@@ -30,8 +32,21 @@ extension DocumentSession {
30 show(location) 32 show(location)
31 return .shown 33 return .shown
32 case "denote": 34 case "denote":
33 let (identifier, search) = Denote.split(link.path)
34 let paths = ((try? workspace?.index.files()) ?? []).map(\.path) 35 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)
35 guard let file = Denote.file(withIdentifier: identifier, in: paths) else { 50 guard let file = Denote.file(withIdentifier: identifier, in: paths) else {
36 return .message("No file has the Denote identifier \(identifier)") 51 return .message("No file has the Denote identifier \(identifier)")
37 } 52 }
Sources/OrgApp/OrgPreferences.swift +9 −1
@@ -174,13 +174,21 @@ public enum OrgPreferences {
174 public static func dailiesEntry(_ defaults: UserDefaults = .standard) -> String { string("dailiesEntry", defaults).nonEmpty ?? "* %?" } 174 public static func dailiesEntry(_ defaults: UserDefaults = .standard) -> String { string("dailiesEntry", defaults).nonEmpty ?? "* %?" }
175 /// Whether the note and daily-note commands follow Denote rather than org-roam. 175 /// Whether the note and daily-note commands follow Denote rather than org-roam.
176 public static func usesDenote(_ defaults: UserDefaults = .standard) -> Bool { string("notesPackage", defaults) == "denote" } 176 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.
178 public static func denoteDirectory(_ defaults: UserDefaults = .standard) -> String { string("denoteDirectory", defaults) } 180 public static func denoteDirectory(_ defaults: UserDefaults = .standard) -> String { string("denoteDirectory", defaults) }
179 /// `denote-journal-directory`, relative to `denote-directory` unless absolute. 181 /// `denote-journal-directory`, relative to `denote-directory` unless absolute.
180 public static func denoteJournalDirectory(_ defaults: UserDefaults = .standard) -> String { string("denoteJournalDirectory", defaults).nonEmpty ?? "journal" } 182 public static func denoteJournalDirectory(_ defaults: UserDefaults = .standard) -> String { string("denoteJournalDirectory", defaults).nonEmpty ?? "journal" }
181 public static func denoteJournalKeyword(_ defaults: UserDefaults = .standard) -> String { string("denoteJournalKeyword", defaults).nonEmpty ?? "journal" } 183 public static func denoteJournalKeyword(_ defaults: UserDefaults = .standard) -> String { string("denoteJournalKeyword", defaults).nonEmpty ?? "journal" }
182 /// `denote-journal-title-format`, a `format-time-string` format. 184 /// `denote-journal-title-format`, a `format-time-string` format.
183 public static func denoteJournalTitle(_ defaults: UserDefaults = .standard) -> String { string("denoteJournalTitle", defaults).nonEmpty ?? "%A %-e %B %Y %H:%M" } 185 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 }
184 /// `denote-prompts`: what a new note asks after its title, in order. 192 /// `denote-prompts`: what a new note asks after its title, in order.
185 public static func denotePrompts(_ defaults: UserDefaults = .standard) -> [String] { 193 public static func denotePrompts(_ defaults: UserDefaults = .standard) -> [String] {
186 string("denotePrompts", defaults).split(whereSeparator: \.isWhitespace).map(String.init) 194 string("denotePrompts", defaults).split(whereSeparator: \.isWhitespace).map(String.init)
Sources/OrgApp/RoamActions.swift +146 −20
@@ -80,6 +80,12 @@ public struct RoamActions {
80 } 80 }
81 case "app.node.rename-from-front-matter": 81 case "app.node.rename-from-front-matter":
82 renameFromFrontMatter() 82 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()
83 case "app.node.find": 89 case "app.node.find":
84 chooseNode("Node: ") { choice in 90 chooseNode("Node: ") { choice in
85 switch choice { 91 switch choice {
@@ -87,6 +93,24 @@ public struct RoamActions {
87 case .created(let path, _, _): open(path, (session.text(of: path).map { ($0 as NSString).length }) ?? 0) 93 case .created(let path, _, _): open(path, (session.text(of: path).map { ($0 as NSString).length }) ?? 0)
88 } 94 }
89 } 95 }
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 }
90 case "app.node.insert": 114 case "app.node.insert":
91 chooseNode("Node: ") { choice in 115 chooseNode("Node: ") { choice in
92 switch choice { 116 switch choice {
@@ -156,8 +180,8 @@ public struct RoamActions {
156 /// `org-roam-node-read`: a node by its title, with its file's name when titles repeat. A 180 /// `org-roam-node-read`: a node by its title, with its file's name when titles repeat. A
157 /// title no node has makes a node with it, as org-roam's default capture template does; 181 /// title no node has makes a node with it, as org-roam's default capture template does;
158 /// with Denote, `denote` asks for its keywords and makes the note. 182 /// with Denote, `denote` asks for its keywords and makes the note.
159 private func chooseNode(_ message: String, _ then: @escaping (NodeChoice) -> Void) { 183 private func chooseNode(_ message: String, silo: String? = nil, _ then: @escaping (NodeChoice) -> Void) {
160 let all = nodes() 184 let all = silo.map { silo in nodes().filter { $0.location.path.hasPrefix(silo.hasSuffix("/") ? silo : silo + "/") } } ?? nodes()
161 let counts = Dictionary(all.map { ($0.title, 1) }, uniquingKeysWith: +) 185 let counts = Dictionary(all.map { ($0.title, 1) }, uniquingKeysWith: +)
162 let labels = all.map { node in 186 let labels = all.map { node in
163 counts[node.title, default: 0] > 1 ? "\(node.title) (\((node.location.path as NSString).lastPathComponent))" : node.title 187 counts[node.title, default: 0] > 1 ? "\(node.title) (\((node.location.path as NSString).lastPathComponent))" : node.title
@@ -167,7 +191,7 @@ public struct RoamActions {
167 if let index = labels.firstIndex(of: answer) { return then(.existing(all[index])) } 191 if let index = labels.firstIndex(of: answer) { return then(.existing(all[index])) }
168 let title = answer.trimmingCharacters(in: .whitespaces) 192 let title = answer.trimmingCharacters(in: .whitespaces)
169 guard !title.isEmpty else { return } 193 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) }
171 guard let folder = RoamNode.directory(roots: roots()) else { return show("No folder for new nodes") } 195 guard let folder = RoamNode.directory(roots: roots()) else { return show("No folder for new nodes") }
172 do { 196 do {
173 let node = try RoamNode.create(title: title, in: folder) 197 let node = try RoamNode.create(title: title, in: folder)
@@ -191,24 +215,33 @@ public struct RoamActions {
191 215
192 /// `denote`: after the title, the questions `denote-prompts` lists, in its order, then the 216 /// `denote`: after the title, the questions `denote-prompts` lists, in its order, then the
193 /// note in `denote-directory` or the folder chosen under it. 217 /// note in `denote-directory` or the folder chosen under it.
194 private func createDenote(_ title: String, known: [IndexStore.Node], _ then: @escaping (NodeChoice) -> Void) { 218 /// In a silo, its folder takes the place of `denote-directory`.
195 guard let root = DenoteNote.directory(roots: roots()) else { return show("No folder for new notes") } 219 /// With `signature`, as `denote-use-signature` sets it: that signature, not asked for.
196 createDenote(title, root: root, prompts: OrgPreferences.denotePrompts(), templates: UserConfig.denoteTemplates(.standard), 220 func createDenote(_ title: String, known: [IndexStore.Node], silo: String? = nil, signature: String? = nil, _ then: @escaping (NodeChoice) -> Void) {
197 keywords: Denote.keywords(known.flatMap { Denote.name(ofFile: $0.location.path).keywords }), then) 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)
198 } 228 }
199 229
230 /// The note goes in the first of `roots`, or the folder the `subdirectory` question picks
231 /// among them and their folders.
200 func createDenote( 232 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],
202 answers: DenoteAnswers = DenoteAnswers(), _ then: @escaping (NodeChoice) -> Void 234 answers: DenoteAnswers = DenoteAnswers(), _ then: @escaping (NodeChoice) -> Void
203 ) { 235 ) {
236 let root = roots[0]
204 func next(_ answers: DenoteAnswers) { 237 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)
206 } 239 }
207 var answers = answers 240 var answers = answers
208 switch prompts.first { 241 switch prompts.first {
209 case nil: 242 case nil:
210 do { 243 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,
212 now: answers.date ?? Date(), signature: answers.signature, template: answers.template) 245 now: answers.date ?? Date(), signature: answers.signature, template: answers.template)
213 refresh() 246 refresh()
214 show("Created \((note.path as NSString).lastPathComponent)") 247 show("Created \((note.path as NSString).lastPathComponent)")
@@ -224,11 +257,11 @@ public struct RoamActions {
224 next(answers) 257 next(answers)
225 } 258 }
226 case "subdirectory": 259 case "subdirectory":
227 let folders = DenoteNote.subdirectories(of: root) 260 let folders = DenoteNote.folderChoices(roots)
228 guard !folders.isEmpty else { return next(answers) } 261 guard folders.count > 1 else { return next(answers) }
229 ask(Prompt(key: "subdirectory", message: "Select SUBDIRECTORY: ", choices: ["."] + folders)) { answer in 262 ask(Prompt(key: "subdirectory", message: "Select SUBDIRECTORY: ", choices: folders.map(\.label))) { answer in
230 guard let answer else { return } 263 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
232 next(answers) 265 next(answers)
233 } 266 }
234 case "date": 267 case "date":
@@ -256,23 +289,116 @@ public struct RoamActions {
256 } 289 }
257 } 290 }
258 291
259 /// `denote-rename-file-using-front-matter`: the open file renamed from its title and 292 /// `denote-rename-file-using-front-matter`: the open file renamed from its title,
260 /// keywords, keeping its identifier and signature. 293 /// keywords and signature, keeping its identifier.
261 func renameFromFrontMatter() { 294 func renameFromFrontMatter() {
262 guard let path = session.path else { return show("No file is open") } 295 guard let path = session.path else { return show("No file is open") }
263 guard let text = session.text(of: path) else { return show("Can't read \((path as NSString).lastPathComponent)") } 296 guard let text = session.text(of: path) else { return show("Can't read \((path as NSString).lastPathComponent)") }
264 guard let target = Denote.renamed(path, text: text) else { return show("Not a Denote note: no front matter or identifier") } 297 guard let target = Denote.renamed(path, text: text) else { return show("Not a Denote note: no front matter or identifier") }
265 guard target != path else { return show("Nothing to rename") } 298 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) {
266 guard !FileManager.default.fileExists(atPath: target) else { return show("\((target as NSString).lastPathComponent) is already there") } 304 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)") }
268 do { 305 do {
269 try FileManager.default.moveItem(atPath: path, toPath: target) 306 try move(path, to: target)
270 session.kill(path)
271 refresh() 307 refresh()
272 open(target, 0) 308 open(target, 0)
273 show("Renamed to \((target as NSString).lastPathComponent)") 309 show("Renamed to \((target as NSString).lastPathComponent)")
274 } catch { 310 } 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: "; "))
276 } 402 }
277 } 403 }
278} 404}
Sources/OrgApp/UserConfig.swift +9 −1
@@ -178,13 +178,21 @@ public enum UserConfig {
178 Setting(section: "", key: "notes-package", defaultsKey: "notesPackage", kind: .choice([("org-roam", "org-roam"), ("denote", "denote")]), 178 Setting(section: "", key: "notes-package", defaultsKey: "notesPackage", kind: .choice([("org-roam", "org-roam"), ("denote", "denote")]),
179 fallback: .string("org-roam"), comment: "whose conventions Find Node, Insert Node Link and the daily-note commands follow: org-roam or denote", legacy: ""), 179 fallback: .string("org-roam"), comment: "whose conventions Find Node, Insert Node Link and the daily-note commands follow: org-roam or denote", legacy: ""),
180 Setting(section: "", key: "denote-directory", defaultsKey: "denoteDirectory", kind: .string, fallback: .string(""), 180 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: ""),
182 Setting(section: "", key: "denote-journal-directory", defaultsKey: "denoteJournalDirectory", kind: .string, fallback: .string("journal"), 184 Setting(section: "", key: "denote-journal-directory", defaultsKey: "denoteJournalDirectory", kind: .string, fallback: .string("journal"),
183 comment: "the folder denote-journal entries are in, relative to denote-directory", legacy: ""), 185 comment: "the folder denote-journal entries are in, relative to denote-directory", legacy: ""),
184 Setting(section: "", key: "denote-journal-keyword", defaultsKey: "denoteJournalKeyword", kind: .string, fallback: .string("journal"), 186 Setting(section: "", key: "denote-journal-keyword", defaultsKey: "denoteJournalKeyword", kind: .string, fallback: .string("journal"),
185 comment: "the keyword journal entries have", legacy: ""), 187 comment: "the keyword journal entries have", legacy: ""),
186 Setting(section: "", key: "denote-prompts", defaultsKey: "denotePrompts", kind: .string, fallback: .string("title keywords"), 188 Setting(section: "", key: "denote-prompts", defaultsKey: "denotePrompts", kind: .string, fallback: .string("title keywords"),
187 comment: "what a new Denote note asks, in order, separated by spaces: title keywords subdirectory date template signature", legacy: ""), 189 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: ""),
188 Setting(section: "", key: "denote-journal-title-format", defaultsKey: "denoteJournalTitle", kind: .string, fallback: .string("%A %-e %B %Y %H:%M"), 196 Setting(section: "", key: "denote-journal-title-format", defaultsKey: "denoteJournalTitle", kind: .string, fallback: .string("%A %-e %B %Y %H:%M"),
189 comment: "a journal entry's title; a format-time-string format", legacy: ""), 197 comment: "a journal entry's title; a format-time-string format", legacy: ""),
190 Setting(section: "", key: "auto-fill-mode", defaultsKey: "autoFill", kind: .bool, fallback: .bool(false), 198 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 {
87 public var tableLinePos: String? 87 public var tableLinePos: String?
88 /// `:time-prompt`: a date tree asks which day the entry is for. 88 /// `:time-prompt`: a date tree asks which day the entry is for.
89 public var timePrompt = false 89 public var timePrompt = false
90 /// `denote-org-capture`: the entry goes in a new Denote note, asked for first.
91 public var denote = false
90 92
91 public init( 93 public init(
92 prepend: Bool = false, immediateFinish: Bool = false, emptyLines: Int? = nil, emptyLinesBefore: Int? = nil, 94 prepend: Bool = false, immediateFinish: Bool = false, emptyLines: Int? = nil, emptyLinesBefore: Int? = nil,
93 emptyLinesAfter: Int? = nil, jumpToCaptured: Bool = false, clockIn: Bool = false, clockKeep: Bool = false, clockResume: Bool = false, 95 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
95 ) { 97 ) {
98 self.denote = denote
96 self.tableLinePos = tableLinePos 99 self.tableLinePos = tableLinePos
97 self.timePrompt = timePrompt 100 self.timePrompt = timePrompt
98 self.prepend = prepend 101 self.prepend = prepend
Sources/OrgCore/Commands/ClockTable.swift +4
@@ -400,6 +400,10 @@ extension EmacsBuffer {
400 try replaceDynamicBlockContent(at: mark.position, with: table, recalculate: table.range(of: "(?mi)^[ \\t]*#\\+TBLFM:", options: .regularExpression) != nil) 400 try replaceDynamicBlockContent(at: mark.position, with: table, recalculate: table.range(of: "(?mi)^[ \\t]*#\\+TBLFM:", options: .regularExpression) != nil)
401 return 401 return
402 } 402 }
403 if DenoteBlocks.names.contains(name) {
404 try replaceDynamicBlockContent(at: begin, with: denoteBlock(name, paramText: paramText))
405 return
406 }
403 guard name == "clocktable" else { throw UserError(message: "Dynamic blocks named \(name) aren't supported") } 407 guard name == "clocktable" else { throw UserError(message: "Dynamic blocks named \(name) aren't supported") }
404 var defaults = ClockTable.Params.defaults 408 var defaults = ClockTable.Params.defaults
405 defaults[":lang"] = .string(options.exportLanguage) 409 defaults[":lang"] = .string(options.exportLanguage)
Sources/OrgCore/Commands/Command.swift +4
@@ -46,6 +46,10 @@ public struct EditingOptions: Sendable, Equatable, Codable {
46 public var archiveLocation: String? 46 public var archiveLocation: String?
47 /// The agenda files (`(org-agenda-files)`), for clock tables over `agenda` scopes; nil for none. 47 /// The agenda files (`(org-agenda-files)`), for clock tables over `agenda` scopes; nil for none.
48 public var agendaFiles: [String]? 48 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
49 /// The file the buffer visits (`buffer-file-name`); nil for a buffer without one. 53 /// The file the buffer visits (`buffer-file-name`); nil for a buffer without one.
50 public var filePath: String? 54 public var filePath: String?
51 /// `org-export-default-language`: the language of exports without `#+LANGUAGE`, and of 55 /// `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 {
12 return nil 12 return nil
13 } 13 }
14 14
15 /// The files under `directories` whose names have an identifier, as Denote lists them.
16 public static func files(in directories: [String]) -> [String] { DenoteBlocks.files(in: directories).map(\.path) }
17
18 /// A query link's regexp, `denote:query-contents:REGEXP` (contents) or
19 /// `denote:query-filenames:REGEXP`; nil for a link to an identifier.
20 public static func query(_ path: String) -> (contents: Bool, regexp: String)? {
21 if path.hasPrefix("query-contents:") { return (true, String(path.dropFirst("query-contents:".count))) }
22 if path.hasPrefix("query-filenames:") { return (false, String(path.dropFirst("query-filenames:".count))) }
23 return nil
24 }
25
15 /// A `denote:` link's path split at `::` into the identifier and the search. 26 /// A `denote:` link's path split at `::` into the identifier and the search.
16 public static func split(_ path: String) -> (identifier: String, search: String?) { 27 public static func split(_ path: String) -> (identifier: String, search: String?) {
17 guard let range = path.range(of: "::") else { return (path, nil) } 28 guard let range = path.range(of: "::") else { return (path, nil) }
@@ -90,12 +101,48 @@ public enum Denote {
90 /// `denote-org-front-matter`, dated as an inactive Org timestamp. The signature line is 101 /// `denote-org-front-matter`, dated as an inactive Org timestamp. The signature line is
91 /// left out when there's none. 102 /// left out when there's none.
92 public static func frontMatter(title: String, date: Date, keywords: [String], identifier: String, signature: String = "", calendar: Calendar = .current) -> String { 103 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) 104 lines(title: title, date: date, keywords: keywords, identifier: identifier, signature: signature, calendar: calendar)
94 let day = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"][c.weekday! - 1] 105 .compactMap(\.line).map { $0 + "\n" }.joined() + "\n"
95 let stamp = String(format: "[%04d-%02d-%02d %@ %02d:%02d]", c.year!, c.month!, c.day!, day, c.hour!, c.minute!) 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 }
96 let tags = keywords.isEmpty ? "" : ":" + keywords.joined(separator: ":") + ":" 116 let tags = keywords.isEmpty ? "" : ":" + keywords.joined(separator: ":") + ":"
97 return "#+title: \(title)\n#+date: \(stamp)\n#+filetags: \(tags)\n#+identifier: \(identifier)\n" 117 return [("title", "#+title: \(title)"), ("date", stamp.map { "#+date: \($0)" }), ("filetags", "#+filetags: \(tags)"),
98 + (signature.isEmpty ? "" : "#+signature: \(signature)\n") + "\n" 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")
99 } 146 }
100 147
101 // MARK: - Reading names and front matter 148 // MARK: - Reading names and front matter
@@ -139,6 +186,13 @@ public enum Denote {
139 return (value("title"), keywords, value("identifier")?.nonEmptyOrNil, value("signature")) 186 return (value("title"), keywords, value("identifier")?.nonEmptyOrNil, value("signature"))
140 } 187 }
141 188
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
142 /// `denote-rename-file-using-front-matter`: the name the file at `path` takes from its 196 /// `denote-rename-file-using-front-matter`: the name the file at `path` takes from its
143 /// front matter's title, keywords and signature, each empty when its line is missing. Nil 197 /// front matter's title, keywords and signature, each empty when its line is missing. Nil
144 /// when the file has no front matter, or no identifier in it or its name. 198 /// 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 {
50 return StoredLink(link: link, description: buffer.substring(title.lowerBound, title.upperBound)) 50 return StoredLink(link: link, description: buffer.substring(title.lowerBound, title.upperBound))
51 } 51 }
52 52
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
53 /// A `<<target>>` on the caret's line that the caret touches, as `org-in-regexp` finds it. 65 /// A `<<target>>` on the caret's line that the caret touches, as `org-in-regexp` finds it.
54 static func targetAtCaret(_ context: EditContext) -> String? { 66 static func targetAtCaret(_ context: EditContext) -> String? {
55 let ns = context.text as NSString 67 let ns = context.text as NSString
@@ -312,7 +324,10 @@ public struct CreateID: OrgCommand {
312extension EmacsBuffer { 324extension EmacsBuffer {
313 /// The entry's own `ID` when it has non-blank one, from point at its heading (or the 325 /// The entry's own `ID` when it has non-blank one, from point at its heading (or the
314 /// start of the file). 326 /// 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? {
316 saveExcursion { 331 saveExcursion {
317 if beforeFirstHeading { 332 if beforeFirstHeading {
318 while bolp, lookingAt("^[ \\t]*#[ \\t]") != nil || lookingAt("^[ \\t]*#$") != nil { if forwardLine(1) != 0 { break } } 333 while bolp, lookingAt("^[ \\t]*#[ \\t]") != nil || lookingAt("^[ \\t]*#$") != nil { if forwardLine(1) != 0 { break } }
@@ -322,8 +337,9 @@ extension EmacsBuffer {
322 } 337 }
323 guard let drawer = looking(Self.propertyDrawerPattern, caseInsensitive: true) else { return nil } 338 guard let drawer = looking(Self.propertyDrawerPattern, caseInsensitive: true) else { return nil }
324 let body = substring(drawer[0]!.lowerBound, drawer[0]!.upperBound) 339 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 } 340 let key = NSRegularExpression.escapedPattern(for: name)
326 return body[range].replacingOccurrences(of: "^[ \\t]*:[Ii][Dd]:[ \\t]+|[ \\t]+$", with: "", options: .regularExpression) 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])
327 } 343 }
328 } 344 }
329} 345}
Sources/OrgEditorAppKit/EditorCommands.swift +18
@@ -122,6 +122,24 @@ public enum EditorCommands {
122 EditorCommand(id: "app.node.find", title: "Find Node…", action: .app), 122 EditorCommand(id: "app.node.find", title: "Find Node…", action: .app),
123 EditorCommand(id: "app.node.insert", title: "Insert Node Link…", action: .app), 123 EditorCommand(id: "app.node.insert", title: "Insert Node Link…", action: .app),
124 EditorCommand(id: "app.node.rename-from-front-matter", title: "Rename Note from Front Matter", action: .app), 124 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),
125 EditorCommand(id: "app.attach.attach", title: "Attach File…", action: .app), 143 EditorCommand(id: "app.attach.attach", title: "Attach File…", action: .app),
126 EditorCommand(id: "app.attach.move", title: "Attach File by Moving…", action: .app), 144 EditorCommand(id: "app.attach.move", title: "Attach File by Moving…", action: .app),
127 EditorCommand(id: "app.attach.link", title: "Attach File as Hard Link…", action: .app), 145 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 {
17 @State private var groups: [CaptureGroup] = [] 17 @State private var groups: [CaptureGroup] = []
18 /// The day `:time-prompt` asked for. 18 /// The day `:time-prompt` asked for.
19 @State private var treeDate: Date? 19 @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?
20 @State private var problem: String? 24 @State private var problem: String?
21 @State private var template: CaptureTemplate? 25 @State private var template: CaptureTemplate?
22 @State private var questions: [Capture.Question] = [] 26 @State private var questions: [Capture.Question] = []
@@ -136,6 +140,7 @@ struct CaptureView: View {
136 } 140 }
137 141
138 static func target(_ template: CaptureTemplate) -> String { 142 static func target(_ template: CaptureTemplate) -> String {
143 if template.options.denote { return "a new Denote note" }
139 let file = (template.target.file as NSString).lastPathComponent 144 let file = (template.target.file as NSString).lastPathComponent
140 switch template.target { 145 switch template.target {
141 case .file, .heading: return file 146 case .file, .heading: return file
@@ -198,7 +203,9 @@ struct CaptureView: View {
198 for heading in DocumentModel(tree: OrgParser.parse(text)).headings { for tag in heading.localTags where !tags.contains(tag) { tags.append(tag) } } 203 for heading in DocumentModel(tree: OrgParser.parse(text)).headings { for tag in heading.localTags where !tags.contains(tag) { tags.append(tag) } }
199 context.fileTags = tags 204 context.fileTags = tags
200 } 205 }
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)
202 answers = questions.map { _ in "" } 209 answers = questions.map { _ in "" }
203 if questions.isEmpty { expand() } 210 if questions.isEmpty { expand() }
204 } 211 }
@@ -211,6 +218,10 @@ struct CaptureView: View {
211 private func expand() { 218 private func expand() {
212 guard let template else { return } 219 guard let template else { return }
213 var answers = answers 220 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 }
214 if asksTreeDate(template) { 225 if asksTreeDate(template) {
215 treeDate = Capture.treeDate(answers.removeFirst(), now: Date()) 226 treeDate = Capture.treeDate(answers.removeFirst(), now: Date())
216 } 227 }
@@ -247,8 +258,20 @@ struct CaptureView: View {
247 guard let template else { return } 258 guard let template else { return }
248 let opened = context.now 259 let opened = context.now
249 let now = Date() 260 let now = Date()
250 let placed = template.resolved(workspace: workspace, session: session, clock: clock).flatMap { resolved in 261 let placed: Result<(path: String, offset: Int), CaptureError>
251 session.capture(text, template: resolved.template, root: workspace.rootPaths.first, file: resolved.file, now: captureDate(now)) 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 }
252 } 275 }
253 switch placed { 276 switch placed {
254 case .failure(let error): 277 case .failure(let error):
Sources/Orgstar/ContentView.swift +7 −3
@@ -71,6 +71,8 @@ struct ContentView: View {
71 ) 71 )
72 // The agenda files, for clock tables over `agenda` scopes. 72 // The agenda files, for clock tables over `agenda` scopes.
73 options.agendaFiles = workspace.agendaFilePaths() 73 options.agendaFiles = workspace.agendaFilePaths()
74 options.denoteDirectories = DenoteNote.directories(roots: workspace.rootPaths)
75 options.denoteSequenceScheme = OrgPreferences.denoteSequenceScheme()
74 options.timer = TimerModel.shared.timer 76 options.timer = TimerModel.shared.timer
75 return options 77 return options
76 } 78 }
@@ -722,7 +724,7 @@ struct ContentView: View {
722 apply: { applyText($0, caret: $1) }, show: { [commands] in commands.show($0) }, ask: { [commands] in commands.ask($0, reply: $1) }, 724 apply: { applyText($0, caret: $1) }, show: { [commands] in commands.show($0) }, ask: { [commands] in commands.ask($0, reply: $1) },
723 storeLink: { [commands] in _ = StoredLink.add($0, to: &commands.storedLinks) }, 725 storeLink: { [commands] in _ = StoredLink.add($0, to: &commands.storedLinks) },
724 open: { [session, workspace, commands] file in 726 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) }
726 }, 728 },
727 reveal: { NSWorkspace.shared.open(URL(fileURLWithPath: $0, isDirectory: true)) }, 729 reveal: { NSWorkspace.shared.open(URL(fileURLWithPath: $0, isDirectory: true)) },
728 pick: { method in 730 pick: { method in
@@ -856,7 +858,7 @@ struct ContentView: View {
856 private func runExternal(_ request: ExternalRequest) { 858 private func runExternal(_ request: ExternalRequest) {
857 switch request { 859 switch request {
858 case .openLink(let link): 860 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) }
860 // `org-occur` for a regexp link, once the editor shows the file. 862 // `org-occur` for a regexp link, once the editor shows the file.
861 if let regexp = Links.regexpSearch(link) { 863 if let regexp = Links.regexpSearch(link) {
862 DispatchQueue.main.async { commands.editor?.perform(SparseTreeCommand(), answers: ["sparse": "/", "regexp": regexp]) } 864 DispatchQueue.main.async { commands.editor?.perform(SparseTreeCommand(), answers: ["sparse": "/", "regexp": regexp]) }
@@ -1125,7 +1127,9 @@ struct ContentView: View {
1125 commands.editor?.perform(InsertLink(stored: commands.storedLinks, file: session.path)) 1127 commands.editor?.perform(InsertLink(stored: commands.storedLinks, file: session.path))
1126 case "org.link.store": 1128 case "org.link.store":
1127 guard let editor = commands.editor, let path = session.path else { return commands.show("No method for storing a link from this buffer") } 1129 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())))
1129 case "org.id.store-link": 1133 case "org.id.store-link":
1130 guard let editor = commands.editor, let path = session.path else { return } 1134 guard let editor = commands.editor, let path = session.path else { return }
1131 if case .commit = editor.perform(CreateID()), 1135 if case .commit = editor.perform(CreateID()),
Sources/Orgstar/LinkOpener.swift +9 −1
@@ -6,13 +6,21 @@ import OrgCore
6@MainActor 6@MainActor
7enum LinkOpener { 7enum LinkOpener {
8 /// Returns a message when the link can't be followed. 8 /// 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? {
10 switch session.follow(link, workspace: workspace, isText: FileTypes.isText) { 11 switch session.follow(link, workspace: workspace, isText: FileTypes.isText) {
11 case .shown: return nil 12 case .shown: return nil
12 case .openExternally(let url): 13 case .openExternally(let url):
13 NSWorkspace.shared.open(url) 14 NSWorkspace.shared.open(url)
14 return nil 15 return nil
15 case .message(let message): return message 16 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
16 } 24 }
17 } 25 }
18} 26}
Sources/OrgstarMobile/CaptureScreen.swift +25 −3
@@ -18,6 +18,10 @@ struct CaptureScreen: View {
18 @State private var groups: [CaptureGroup] = [] 18 @State private var groups: [CaptureGroup] = []
19 /// The day `:time-prompt` asked for. 19 /// The day `:time-prompt` asked for.
20 @State private var treeDate: Date? 20 @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?
21 /// The filed entry, while its refile target is picked. 25 /// The filed entry, while its refile target is picked.
22 @State private var refiling: RefileEntry? 26 @State private var refiling: RefileEntry?
23 @State private var key: String? 27 @State private var key: String?
@@ -127,7 +131,9 @@ struct CaptureScreen: View {
127 for heading in DocumentModel(tree: OrgParser.parse(source)).headings { for tag in heading.localTags where !tags.contains(tag) { tags.append(tag) } } 131 for heading in DocumentModel(tree: OrgParser.parse(source)).headings { for tag in heading.localTags where !tags.contains(tag) { tags.append(tag) } }
128 context.fileTags = tags 132 context.fileTags = tags
129 } 133 }
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)
131 answers = questions.map { _ in "" } 137 answers = questions.map { _ in "" }
132 treeDate = nil 138 treeDate = nil
133 editing = false 139 editing = false
@@ -146,6 +152,10 @@ struct CaptureScreen: View {
146 private func fill() { 152 private func fill() {
147 guard let template else { return } 153 guard let template else { return }
148 var answers = answers 154 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 }
149 if asksTreeDate(template) { treeDate = Capture.treeDate(answers.removeFirst(), now: Date()) } 159 if asksTreeDate(template) { treeDate = Capture.treeDate(answers.removeFirst(), now: Date()) }
150 context.now = captureDate 160 context.now = captureDate
151 switch Capture.fill(template.template, context: context, answers: answers) { 161 switch Capture.fill(template.template, context: context, answers: answers) {
@@ -186,8 +196,20 @@ struct CaptureScreen: View {
186 private func file(refile: Bool = false) { 196 private func file(refile: Bool = false) {
187 guard let template else { return } 197 guard let template else { return }
188 let now = Date() 198 let now = Date()
189 let placed = template.resolved(workspace: workspace, session: session, clock: clock).flatMap { resolved in 199 let placed: Result<(path: String, offset: Int), CaptureError>
190 session.capture(text, template: resolved.template, root: workspace.rootPaths.first, file: resolved.file, now: treeDate ?? request.day.map(Self.date) ?? now) 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 }
191 } 213 }
192 switch placed { 214 switch placed {
193 case .failure(let error): 215 case .failure(let error):
Sources/OrgstarMobile/EditorScreen.swift +29 −1
@@ -45,6 +45,8 @@ struct EditorScreen: View {
45 var options = session.options 45 var options = session.options
46 options.filePath = path 46 options.filePath = path
47 options.agendaFiles = workspace.agendaFilePaths() 47 options.agendaFiles = workspace.agendaFilePaths()
48 options.denoteDirectories = DenoteNote.directories(roots: workspace.rootPaths)
49 options.denoteSequenceScheme = OrgPreferences.denoteSequenceScheme()
48 options.timer = TimerModel.shared.timer 50 options.timer = TimerModel.shared.timer
49 return options 51 return options
50 } 52 }
@@ -333,7 +335,9 @@ struct EditorScreen: View {
333 guard let editor else { return } 335 guard let editor else { return }
334 switch id { 336 switch id {
335 case "org.link.store": 337 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)
337 case "org.id.store-link": 341 case "org.id.store-link":
338 if case .commit = editor.perform(CreateID()), 342 if case .commit = editor.perform(CreateID()),
339 let link = Links.storeID(in: editor.editContext(), fileName: (path as NSString).lastPathComponent) { 343 let link = Links.storeID(in: editor.editContext(), fileName: (path as NSString).lastPathComponent) {
@@ -475,6 +479,12 @@ extension EditorScreen {
475 model.openRequest = .offset(target, caret) 479 model.openRequest = .offset(target, caret)
476 case .openExternally(let url): if url.isFileURL { previewed = url } else { openURL(url) } 480 case .openExternally(let url): if url.isFileURL { previewed = url } else { openURL(url) }
477 case .message(let text): message = text 481 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 }
478 } 488 }
479 } 489 }
480 490
@@ -932,6 +942,24 @@ struct CommandPalette: View {
932 ("app.crypt.encrypt-entries", "Encrypt Tagged Entries…"), ("app.crypt.forget-passphrase", "Forget Encryption Passphrase"), 942 ("app.crypt.encrypt-entries", "Encrypt Tagged Entries…"), ("app.crypt.forget-passphrase", "Forget Encryption Passphrase"),
933 ("app.backlinks", "Show Backlinks"), ("app.node.find", "Find Node…"), ("app.node.insert", "Insert Node Link…"), 943 ("app.backlinks", "Show Backlinks"), ("app.node.find", "Find Node…"), ("app.node.insert", "Insert Node Link…"),
934 ("app.node.rename-from-front-matter", "Rename Note from Front Matter"), 944 ("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…"),
935 ("app.dailies.today", "Go to Today's Daily Note"), ("app.dailies.yesterday", "Go to Yesterday's Daily Note"), 963 ("app.dailies.today", "Go to Today's Daily Note"), ("app.dailies.yesterday", "Go to Yesterday's Daily Note"),
936 ("app.dailies.tomorrow", "Go to Tomorrow's Daily Note"), ("app.dailies.date", "Go to Daily Note for Date…"), 964 ("app.dailies.tomorrow", "Go to Tomorrow's Daily Note"), ("app.dailies.date", "Go to Daily Note for Date…"),
937 ("app.dailies.capture-today", "Capture to Today's Daily Note"), ("app.dailies.capture-yesterday", "Capture to Yesterday's Daily Note"), 965 ("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 {
407 "app.attach.new", "app.attach.open", "app.attach.reveal", "app.attach.delete", "app.attach.delete-all", "app.attach.sync", 407 "app.attach.new", "app.attach.open", "app.attach.reveal", "app.attach.delete", "app.attach.delete-all", "app.attach.sync",
408 "app.attach.set-directory", "app.attach.unset-directory", "app.backlinks", "app.node.find", "app.node.insert", 408 "app.attach.set-directory", "app.attach.unset-directory", "app.backlinks", "app.node.find", "app.node.insert",
409 "app.node.rename-from-front-matter": return onAppCommand != nil 409 "app.node.rename-from-front-matter": return onAppCommand != nil
410 case _ where id.hasPrefix("app.node."): return onAppCommand != nil
410 case _ where id.hasPrefix("app.dailies."): return onAppCommand != nil 411 case _ where id.hasPrefix("app.dailies."): return onAppCommand != nil
411 case "app.crypt.encrypt-entry": return onAppCommand != nil && OrgCrypt.heading(context.text, at: context.caret) != nil && OrgCrypt.encryptedRange(context.text, at: context.caret) == nil 412 case "app.crypt.encrypt-entry": return onAppCommand != nil && OrgCrypt.heading(context.text, at: context.caret) != nil && OrgCrypt.encryptedRange(context.text, at: context.caret) == nil
412 case "app.crypt.open-entry", "app.crypt.decrypt-entry": return onAppCommand != nil && OrgCrypt.encryptedRange(context.text, at: context.caret) != nil 413 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 {
382 } 382 }
383 case .openExternally(let target): openURL(target) 383 case .openExternally(let target): openURL(target)
384 case .message(let text): message = text 384 case .message(let text): message = text
385 case .choose(let question, let paths): message = question + paths.map { ($0 as NSString).lastPathComponent }.joined(separator: ", ")
385 } 386 }
386 return .handled 387 return .handled
387 } 388 }
Tests/OrgAppTests/AppTests.swift +5 −1
@@ -1426,7 +1426,7 @@ struct LinkFollowTests {
1426 let notes = try Folder() 1426 let notes = try Folder()
1427 let a = try notes.write("a.org", "* Start\n") 1427 let a = try notes.write("a.org", "* Start\n")
1428 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") 1428 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")
1430 let workspace = try WorkspaceModel(directory: nil) 1430 let workspace = try WorkspaceModel(directory: nil)
1431 try await workspace.addRoot(notes.url) 1431 try await workspace.addRoot(notes.url)
1432 let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r"))) 1432 let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
@@ -1438,6 +1438,10 @@ struct LinkFollowTests {
1438 #expect(follow("denote:20261119T120000::#in") == .shown && session.path == note.path) 1438 #expect(follow("denote:20261119T120000::#in") == .shown && session.path == note.path)
1439 #expect(session.revealRequest?.offset == (try String(contentsOfFile: note.path, encoding: .utf8) as NSString).range(of: "* Inside").location) 1439 #expect(session.revealRequest?.offset == (try String(contentsOfFile: note.path, encoding: .utf8) as NSString).range(of: "* Inside").location)
1440 #expect(follow("denote:20200101T000000") == .message("No file has the Denote identifier 20200101T000000")) 1440 #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"))
1441 } 1445 }
1442 1446
1443 @Test func followsAttachmentAndRadioLinks() throws { 1447 @Test func followsAttachmentAndRadioLinks() throws {
Tests/OrgAppTests/DailiesTests.swift +149 −2
@@ -72,6 +72,23 @@ struct DailiesTests {
72 #expect(try (journal.neighbor(of: made.path, by: -1) as NSString).lastPathComponent == "20261009T120000--friday-9-october-2026-1200__journal.org") 72 #expect(try (journal.neighbor(of: made.path, by: -1) as NSString).lastPathComponent == "20261009T120000--friday-9-october-2026-1200__journal.org")
73 } 73 }
74 74
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
75 @Test func newDenoteNote() throws { 92 @Test func newDenoteNote() throws {
76 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-denote-\(UUID().uuidString)").path 93 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-denote-\(UUID().uuidString)").path
77 defer { try? FileManager.default.removeItem(atPath: folder) } 94 defer { try? FileManager.default.removeItem(atPath: folder) }
@@ -82,13 +99,143 @@ struct DailiesTests {
82 let again = try DenoteNote.create(title: "Field Notes", keywords: ["work", "ideas"], in: folder, now: Self.day) 99 let again = try DenoteNote.create(title: "Field Notes", keywords: ["work", "ideas"], in: folder, now: Self.day)
83 #expect((again.path as NSString).lastPathComponent == "20261011T120001--field-notes__ideas_work.org") 100 #expect((again.path as NSString).lastPathComponent == "20261011T120001--field-notes__ideas_work.org")
84 let sub = (folder as NSString).appendingPathComponent("projects") 101 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")
86 #expect((other.path as NSString).lastPathComponent == "20261011T120002==two=words--plan.org") 103 #expect((other.path as NSString).lastPathComponent == "20261011T120002==two=words--plan.org")
87 #expect(try String(contentsOfFile: other.path, encoding: .utf8) 104 #expect(try String(contentsOfFile: other.path, encoding: .utf8)
88 == "#+title: Plan\n#+date: [2026-10-11 Sun 12:00]\n#+filetags: \n#+identifier: 20261011T120002\n#+signature: two=words\n\n* Goals\n") 105 == "#+title: Plan\n#+date: [2026-10-11 Sun 12:00]\n#+filetags: \n#+identifier: 20261011T120002\n#+signature: two=words\n\n* Goals\n")
89 #expect(DenoteNote.subdirectories(of: folder) == ["projects"]) 106 #expect(DenoteNote.subdirectories(of: folder) == ["projects"])
90 } 107 }
91 108
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
92 /// `denote-prompts` sets the questions after the title and their order. 239 /// `denote-prompts` sets the questions after the title and their order.
93 @MainActor 240 @MainActor
94 @Test func denotePromptsInOrder() throws { 241 @Test func denotePromptsInOrder() throws {
@@ -101,7 +248,7 @@ struct DailiesTests {
101 let actions = RoamActions(session: DocumentSession(recovery: FileRecoveryStore(directory: folder.appendingPathComponent(".r"))), 248 let actions = RoamActions(session: DocumentSession(recovery: FileRecoveryStore(directory: folder.appendingPathComponent(".r"))),
102 roots: { [folder.path] }, nodes: { [] }, show: { _ in }, ask: { prompt, reply in asked.append(prompt.key); reply(answers[prompt.key]) }, 249 roots: { [folder.path] }, nodes: { [] }, show: { _ in }, ask: { prompt, reply in asked.append(prompt.key); reply(answers[prompt.key]) },
103 open: { _, _ in }, insertLink: { _, _ in }, refresh: {}) 250 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"],
105 templates: [("report", "* R\n"), ("memo", "* M\n")], keywords: []) { choice in 252 templates: [("report", "* R\n"), ("memo", "* M\n")], keywords: []) { choice in
106 if case .created(let path, _, _) = choice { created = path } 253 if case .created(let path, _, _) = choice { created = path }
107 } 254 }
Tests/OrgAppTests/DenoteOracleTests.swift +165 −4
@@ -1,11 +1,13 @@
1import Foundation 1import Foundation
2import Testing 2import Testing
3@testable import OrgApp 3@testable import OrgApp
4import OrgCore 4@testable import OrgCore
5 5
6/// Denote and denote-journal themselves, run in Emacs, when they're installed: the load-path 6/// Denote and denote-journal themselves, run in Emacs, when they're installed: the load-path
7/// directories in `ORGSTAR_DENOTE` (colon-separated), else a Doom or package.el install. 7/// directories in `ORGSTAR_DENOTE` (colon-separated), else a Doom or package.el install.
8struct DenoteOracleTests { 8struct DenoteOracleTests {
9 /// The load-path directories of denote and denote-journal, and of denote-org and
10 /// denote-sequence when they're there too.
9 static let loadPath: [String]? = { 11 static let loadPath: [String]? = {
10 if let paths = ProcessInfo.processInfo.environment["ORGSTAR_DENOTE"] { return paths.split(separator: ":").map(String.init) } 12 if let paths = ProcessInfo.processInfo.environment["ORGSTAR_DENOTE"] { return paths.split(separator: ":").map(String.init) }
11 let fm = FileManager.default, home = NSHomeDirectory() 13 let fm = FileManager.default, home = NSHomeDirectory()
@@ -14,15 +16,17 @@ struct DenoteOracleTests {
14 } + ["\(home)/.emacs.d/elpa", "\(home)/.config/emacs/elpa"] 16 } + ["\(home)/.emacs.d/elpa", "\(home)/.config/emacs/elpa"]
15 for root in roots { 17 for root in roots {
16 let names = (try? fm.contentsOfDirectory(atPath: root)) ?? [] 18 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
18 names.filter { $0 == package || ($0.hasPrefix(package + "-") && $0.dropFirst(package.count + 1).first?.isNumber == true) } 20 names.filter { $0 == package || ($0.hasPrefix(package + "-") && $0.dropFirst(package.count + 1).first?.isNumber == true) }
19 .sorted().last.map { "\(root)/\($0)" } 21 .sorted().last.map { "\(root)/\($0)" }
20 } 22 }
21 if dirs.count == 2 { return dirs } 23 if dirs.count >= 2, dirs[0].hasSuffix("/denote") || dirs[0].contains("/denote-") { return dirs }
22 } 24 }
23 return nil 25 return nil
24 }() 26 }()
25 27
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
26 static var enabled: Bool { loadPath != nil && ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil } 30 static var enabled: Bool { loadPath != nil && ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil }
27 31
28 /// Runs `body` with Denote loaded, `denote-directory` at `folder` and nothing backed up. 32 /// Runs `body` with Denote loaded, `denote-directory` at `folder` and nothing backed up.
@@ -111,7 +115,7 @@ struct DenoteOracleTests {
111 (save-buffer)) 115 (save-buffer))
112 """) 116 """)
113 let date = try #require(RoamActions.date("2026-10-11 09:30")) 117 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],
115 now: date, signature: "Part One", template: template) 119 now: date, signature: "Part One", template: template)
116 let names = try FileManager.default.contentsOfDirectory(atPath: theirs.appendingPathComponent("work").path) 120 let names = try FileManager.default.contentsOfDirectory(atPath: theirs.appendingPathComponent("work").path)
117 #expect(names.count == 1) 121 #expect(names.count == 1)
@@ -121,4 +125,161 @@ struct DenoteOracleTests {
121 == String(contentsOf: theirs.appendingPathComponent("work/" + name), encoding: .utf8), "\(name)") 125 == String(contentsOf: theirs.appendingPathComponent("work/" + name), encoding: .utf8), "\(name)")
122 } 126 }
123 } 127 }
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 }
124} 285}
Tests/OrgAppTests/EmacsImportTests.swift +2
@@ -272,12 +272,14 @@ struct EmacsImportTests {
272 (setq denote-directory "~/notes/") 272 (setq denote-directory "~/notes/")
273 (setq denote-journal-directory "~/notes/journal/" denote-journal-keyword "diary") 273 (setq denote-journal-directory "~/notes/journal/" denote-journal-keyword "diary")
274 (setq denote-journal-title-format 'day-date-month-year-24h) 274 (setq denote-journal-title-format 'day-date-month-year-24h)
275 (setq denote-journal-interval 'weekly)
275 """#.write(to: folder.appendingPathComponent("init.el"), atomically: true, encoding: .utf8) 276 """#.write(to: folder.appendingPathComponent("init.el"), atomically: true, encoding: .utf8)
276 let s = settings(EmacsImport.scan(EmacsImport.files(in: folder))) 277 let s = settings(EmacsImport.scan(EmacsImport.files(in: folder)))
277 #expect(s["denote-directory"] == .string("~/notes/")) 278 #expect(s["denote-directory"] == .string("~/notes/"))
278 #expect(s["denote-journal-directory"] == .string("~/notes/journal/")) 279 #expect(s["denote-journal-directory"] == .string("~/notes/journal/"))
279 #expect(s["denote-journal-keyword"] == .string("diary")) 280 #expect(s["denote-journal-keyword"] == .string("diary"))
280 #expect(s["denote-journal-title-format"] == .string("%A %-e %B %Y %H:%M")) 281 #expect(s["denote-journal-title-format"] == .string("%A %-e %B %Y %H:%M"))
282 #expect(s["denote-journal-interval"] == .string("weekly"))
281 } 283 }
282 284
283 @MainActor 285 @MainActor
Tests/OrgCoreTests/LinkStoreTests.swift +18
@@ -231,3 +231,21 @@ struct LinkStoreTests {
231 #expect(links == [a, b]) 231 #expect(links == [a, b])
232 } 232 }
233} 233}
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]].
1071| Next Daily Note (=app.dailies.next=) | =C-c n d f= | — | =SPC n r d f= (N) | =org-roam-dailies-goto-next-note=. | 1071| Next Daily Note (=app.dailies.next=) | =C-c n d f= | — | =SPC n r d f= (N) | =org-roam-dailies-goto-next-note=. |
1072| Previous Daily Note (=app.dailies.previous=) | =C-c n d b= | — | =SPC n r d b= (N) | =org-roam-dailies-goto-previous-note=. | 1072| Previous Daily Note (=app.dailies.previous=) | =C-c n d b= | — | =SPC n r d b= (N) | =org-roam-dailies-goto-previous-note=. |
1073| Rename Note from Front Matter (=app.node.rename-from-front-matter=) | — | — | — | =denote-rename-file-using-front-matter=. | 1073| 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=. |
1074 1092
1075** Unbound commands 1093** Unbound commands
1076 1094
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
112| =name= | string | The name in the list; the key when omitted | description | 112| =name= | string | The name in the list; the key when omitted | description |
113| =type= | string | =entry= (the default), =item=, =checkitem=, =plain= or =table-line= | type | 113| =type= | string | =entry= (the default), =item=, =checkitem=, =plain= or =table-line= | type |
114| =template= | string, required | The text to fill; see [[*Template escapes][Template escapes]] | template | 114| =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 |
116| =headline= | string | A heading in =file= | =file+headline= | 116| =headline= | string | A heading in =file= | =file+headline= |
117| =olp= | string | An outline path in =file=, titles separated by =/= | =file+olp= | 117| =olp= | string | An outline path in =file=, titles separated by =/= | =file+olp= |
118| =datetree= | boolean | Today's entry in a date tree in =file=, under =olp= if given | =file+olp+datetree= | 118| =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
121| =regexp= | string | After the first match of an Emacs regexp in =file= | =file+regexp= | 121| =regexp= | string | After the first match of an Emacs regexp in =file= | =file+regexp= |
122| =id= | string | The heading with this =ID= property, in any file | =id= | 122| =id= | string | The heading with this =ID= property, in any file | =id= |
123| =clock= | boolean | The entry the clock is running in | =clock= | 123| =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= |
124| =prepend= | boolean | Put the text first rather than last | =:prepend= | 125| =prepend= | boolean | Put the text first rather than last | =:prepend= |
125| =immediate-finish= | boolean | File without showing the editor | =:immediate-finish= | 126| =immediate-finish= | boolean | File without showing the editor | =:immediate-finish= |
126| =empty-lines= | integer | Blank lines before and after the captured text | =:empty-lines= | 127| =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
369 punctuation, words joined by =-=; the keywords sorted, each one word, joined by =_=. 369 punctuation, words joined by =-=; the keywords sorted, each one word, joined by =_=.
370- The daily-note commands work on denote-journal's entries: notes in 370- The daily-note commands work on denote-journal's entries: notes in
371 =denote-journal-directory= (=journal=, under =denote-directory=) with the 371 =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 372 =denote-journal-keyword= (=journal=). With =denote-journal-interval= (=daily=), one entry
373 date; a new one is titled by =denote-journal-title-format= (="%A %-e %B %Y %H:%M"=). Capturing 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
374 adds =org-roam-dailies-entry= as for org-roam. 377 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.
375- Rename Note from Front Matter renames the open file from its =#+title:=, 393- Rename Note from Front Matter renames the open file from its =#+title:=,
376 =#+filetags:= and =#+signature:=, keeping its identifier, as 394 =#+filetags:= and =#+signature:=, keeping its identifier, as
377 =denote-rename-file-using-front-matter= does. A missing line leaves that part out of 395 =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 396 the name, and the keywords keep their order.
379 identifier. 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.
380 415
381Import from Emacs reads =denote-directory=, =denote-prompts=, =denote-templates=, 416*** Capture
382=denote-journal-directory=, =denote-journal-keyword= and =denote-journal-title-format=. 417
383Templates that are functions, and Denote notes in Markdown or plain text, are not 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
384supported. 450supported.
385 451
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
386* Inline images 488* Inline images
387 489
388=org-toggle-inline-images= shows image links as images. 490=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
179| =org-track-ordered-property-with-tag= | | 179| =org-track-ordered-property-with-tag= | |
180| =org-timer-format=, =org-timer-default-timer= | | 180| =org-timer-format=, =org-timer-default-timer= | |
181| =org-roam-directory=, =org-roam-dailies-directory=, =org-roam-dailies-file=, =org-roam-dailies-head=, =org-roam-dailies-entry= | | 181| =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= | |
183| =org-attach-id-dir=, =org-attach-use-inheritance= | | 183| =org-attach-id-dir=, =org-attach-use-inheritance= | |
184| =org-yank-image-save-method=, =org-yank-dnd-method= | | 184| =org-yank-image-save-method=, =org-yank-dnd-method= | |
185| =org-crypt-tag-matcher= | | 185| =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
240| =org-roam-dailies-head= | string | ="#+title: %<%Y-%m-%d>\n"= | What a new daily note starts with, under its =ID=. | 240| =org-roam-dailies-head= | string | ="#+title: %<%Y-%m-%d>\n"= | What a new daily note starts with, under its =ID=. |
241| =org-roam-dailies-entry= | string | ="* %?"= | The capture template Capture to Daily Note files. See [[file:09-links.org][Links]]. | 241| =org-roam-dailies-entry= | string | ="* %?"= | The capture template Capture to Daily Note files. See [[file:09-links.org][Links]]. |
242| =notes-package= | string | ="org-roam"= | Whose conventions Find Node…, Insert Node Link… and the daily-note commands follow: ="org-roam"= or ="denote"=. | 242| =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=. |
244| =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=. | 246| =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=. |
245| =denote-journal-directory= | string | ="journal"= | The folder journal entries are in, relative to =denote-directory=. Mirrors =denote-journal-directory=. | 247| =denote-journal-directory= | string | ="journal"= | The folder journal entries are in, relative to =denote-directory=. Mirrors =denote-journal-directory=. |
246| =denote-journal-keyword= | string | ="journal"= | The keyword journal entries have. Mirrors =denote-journal-keyword=. | 248| =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=. |
247| =denote-journal-title-format= | string | ="%A %-e %B %Y %H:%M"= | A new journal entry's title, a =format-time-string= format. | 250| =denote-journal-title-format= | string | ="%A %-e %B %Y %H:%M"= | A new journal entry's title, a =format-time-string= format. |
248| =org-timer-format= | string | ="%s "= | What Insert Timer Value writes, with =%s= for the =h:mm:ss= value. Mirrors =org-timer-format=. | 251| =org-timer-format= | string | ="%s "= | What Insert Timer Value writes, with =%s= for the =h:mm:ss= value. Mirrors =org-timer-format=. |
249| =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=. | 252| =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=, =
638| =org-roam-directory=, =org-roam-dailies-directory= | The same keys, when the value is a string or a form that makes one | 641| =org-roam-directory=, =org-roam-dailies-directory= | The same keys, when the value is a string or a form that makes one |
639| =denote-directory=, =denote-journal-directory=, =denote-journal-keyword= | The same keys, when the value is a string | 642| =denote-directory=, =denote-journal-directory=, =denote-journal-keyword= | The same keys, when the value is a string |
640| =denote-prompts= | The same key, the symbols separated by spaces | 643| =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 |
641| =denote-templates= | =[denote-templates]=: entries whose text is a string or =concat= of strings; a function is listed as unsupported | 646| =denote-templates= | =[denote-templates]=: entries whose text is a string or =concat= of strings; a function is listed as unsupported |
642| =denote-journal-title-format= | The same key; the symbols =day-date-month-year=, =-24h= and =-12h= become their formats | 647| =denote-journal-title-format= | The same key; the symbols =day-date-month-year=, =-24h= and =-12h= become their formats |
643| =org-roam-dailies-capture-templates= | =org-roam-dailies-file=, =-head= and =-entry=, from the first template's =(file+head NAME HEAD)= target and template | 648| =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
235 235
236- Formulas outside orgstar's own calculator go to Emacs on the Mac and are refused on iOS. 236- Formulas outside orgstar's own calculator go to Emacs on the Mac and are refused on iOS.
237- Clock tables support the scopes =nil=, =file=, =subtree= and =treeN=; other scopes, =:match= and =:step= aren't supported. 237- 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.
239 239
240Other: 240Other:
241 241