Commit 9fcd8f0f4d

9fcd8f0f4d658f3a17afc9b50168133eedf00bc8

parent: a7dad05235

Verified · cmc

cmc <hello@cleberg.net> · 2026-11-19 20:32 UTC

Denote prompts, templates, signatures and dates

- denote-prompts sets the questions a new note asks after its title, in
  order: keywords, subdirectory, date, template, signature.
- [denote-templates] in config.toml: text after the front matter.
- Signatures go in the name and a #+signature: line.
- New notes take the first unused identifier, as Denote does.
- Emacs import reads denote-prompts and string or concat templates.
- Oracle test against Denote for a note with all of these.

Layout: unified · split

Sources/OrgApp/ConfigSync.swift +3
@@ -141,6 +141,9 @@ public final class ConfigSync {
141 for template in UserConfig.structureTemplates(defaults) where values[UserConfig.path(UserConfig.structureTemplateTable, template.key)] != .string(template.type) { 141 for template in UserConfig.structureTemplates(defaults) where values[UserConfig.path(UserConfig.structureTemplateTable, template.key)] != .string(template.type) {
142 current = UserConfig.setting(current, section: UserConfig.structureTemplateTable, key: template.key, to: .string(template.type)) 142 current = UserConfig.setting(current, section: UserConfig.structureTemplateTable, key: template.key, to: .string(template.type))
143 } 143 }
144 for template in UserConfig.denoteTemplates(defaults) where values[UserConfig.path(UserConfig.denoteTemplateTable, template.key)] != .string(template.text) {
145 current = UserConfig.setting(current, section: UserConfig.denoteTemplateTable, key: template.key, to: .string(template.text))
146 }
144 guard current != original else { return } 147 guard current != original else { return }
145 text = current 148 text = current
146 try? current.write(to: target, atomically: true, encoding: .utf8) 149 try? current.write(to: target, atomically: true, encoding: .utf8)
Sources/OrgApp/DenoteNote.swift +36 −8
@@ -1,9 +1,9 @@
1import Foundation 1import Foundation
2import OrgCore 2import OrgCore
3 3
4/// A new Denote note, as `denote` makes it with the default `denote-prompts` (title and 4/// A new Denote note, as `denote` makes it: `IDENTIFIER==signature--title__keywords.org` in
5/// keywords): `IDENTIFIER--title__keywords.org` in `denote-directory`, starting with the 5/// `denote-directory` or a folder under it, starting with the Org front matter and then the
6/// Org front matter. 6/// template.
7public enum DenoteNote { 7public enum DenoteNote {
8 /// `denote-directory`: the setting, else the first folder. 8 /// `denote-directory`: the setting, else the first folder.
9 public static func directory(roots: [String], defaults: UserDefaults = .standard) -> String? { 9 public static func directory(roots: [String], defaults: UserDefaults = .standard) -> String? {
@@ -11,15 +11,43 @@ public enum DenoteNote {
11 return denote.isEmpty ? roots.first : OrgAttach.expand(denote, in: roots.first ?? NSHomeDirectory()) 11 return denote.isEmpty ? roots.first : OrgAttach.expand(denote, in: roots.first ?? NSHomeDirectory())
12 } 12 }
13 13
14 /// Makes the note's file in `folder`. Fails rather than replace a file that's there. 14 /// `denote-directory-subdirectories`: the folders under `root`, relative to it, without
15 public static func create(title: String, keywords: [String], in folder: String, now: Date = Date()) throws -> (path: String, id: String) { 15 /// hidden ones.
16 let id = Denote.identifier(for: now) 16 public static func subdirectories(of root: String) -> [String] {
17 let url = URL(fileURLWithPath: root)
18 guard let walk = FileManager.default.enumerator(at: url, includingPropertiesForKeys: [.isDirectoryKey], options: [.skipsHiddenFiles, .skipsPackageDescendants]) else { return [] }
19 var found: [String] = []
20 for case let item as URL in walk where (try? item.resourceValues(forKeys: [.isDirectoryKey]))?.isDirectory == true {
21 found.append(String(item.standardizedFileURL.path.dropFirst(url.standardizedFileURL.path.count + 1)))
22 }
23 return found.sorted()
24 }
25
26 /// The identifiers in the names of the files under `root`.
27 static func identifiers(under root: String) -> Set<String> {
28 guard let walk = FileManager.default.enumerator(atPath: root) else { return [] }
29 var found = Set<String>()
30 for case let path as String in walk { if let id = Denote.identifier(ofFile: path) { found.insert(id) } }
31 return found
32 }
33
34 /// 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
36 /// `root` has; the front matter keeps `now`. Fails rather than replace a file.
37 public static func create(
38 title: String, keywords: [String], in folder: String, root: String? = nil, now: Date = Date(), signature: String = "", template: String = ""
39 ) throws -> (path: String, id: String) {
40 let used = identifiers(under: root ?? folder)
41 var stamp = now
42 while used.contains(Denote.identifier(for: stamp)) { stamp += 1 }
43 let id = Denote.identifier(for: stamp)
17 let keywords = Denote.keywords(keywords) 44 let keywords = Denote.keywords(keywords)
18 let name = Denote.fileName(identifier: id, title: title, keywords: keywords) 45 let signature = Denote.signature(signature)
46 let name = Denote.fileName(identifier: id, signature: signature, title: title, keywords: keywords)
19 let path = (folder as NSString).appendingPathComponent(name) 47 let path = (folder as NSString).appendingPathComponent(name)
20 try FileManager.default.createDirectory(atPath: folder, withIntermediateDirectories: true) 48 try FileManager.default.createDirectory(atPath: folder, withIntermediateDirectories: true)
21 guard !FileManager.default.fileExists(atPath: path) else { throw Dailies.Failure("\(name) is already there") } 49 guard !FileManager.default.fileExists(atPath: path) else { throw Dailies.Failure("\(name) is already there") }
22 let text = Denote.frontMatter(title: title, date: now, keywords: keywords, identifier: id) 50 let text = Denote.frontMatter(title: title, date: now, keywords: keywords, identifier: id, signature: signature) + template
23 try Data(text.utf8).write(to: URL(fileURLWithPath: path), options: .withoutOverwriting) 51 try Data(text.utf8).write(to: URL(fileURLWithPath: path), options: .withoutOverwriting)
24 return (path, id) 52 return (path, id)
25 } 53 }
Sources/OrgApp/EmacsImport.swift +38 −2
@@ -21,6 +21,8 @@ public struct EmacsImport: Sendable {
21 case view(name: String, toml: String) 21 case view(name: String, toml: String)
22 /// A `[[publish]]` table for config.toml. 22 /// A `[[publish]]` table for config.toml.
23 case publish(name: String, toml: String) 23 case publish(name: String, toml: String)
24 /// A `[denote-templates]` entry for config.toml.
25 case denoteTemplate(key: String, text: String)
24 } 26 }
25 27
26 public struct Item: Sendable, Identifiable { 28 public struct Item: Sendable, Identifiable {
@@ -564,6 +566,28 @@ public struct EmacsImport: Sendable {
564 let formats = ["day-date-month-year": "%A %-e %B %Y", "day-date-month-year-24h": "%A %-e %B %Y %H:%M", 566 let formats = ["day-date-month-year": "%A %-e %B %Y", "day-date-month-year-24h": "%A %-e %B %Y %H:%M",
565 "day-date-month-year-12h": "%A %-e %B %Y %I:%M %p", "day": "%A"] 567 "day-date-month-year-12h": "%A %-e %B %Y %I:%M %p", "day": "%A"]
566 if let format = value.string ?? value.symbol.flatMap({ formats[$0] }) { add(name, .string(format)) } else { note("not a format or a known style") } 568 if let format = value.string ?? value.symbol.flatMap({ formats[$0] }) { add(name, .string(format)) } else { note("not a format or a known style") }
569 case "denote-prompts":
570 guard let prompts = value.elements, prompts.allSatisfy({ $0.symbol != nil }) else { return note("not a list of prompts") }
571 add(name, .string(prompts.compactMap(\.symbol).joined(separator: " ")))
572 case "denote-templates":
573 guard let entries = value.elements else { return note("not a list of (KEY . TEXT)") }
574 for entry in entries {
575 guard case .dotted(let head, let tail) = entry, head.count == 1, let key = head[0].symbol else {
576 note("an entry that isn't (KEY . TEXT)")
577 continue
578 }
579 guard let text = tail.string else {
580 unsupported.append(Note(id: id(), name: "Denote template \(key)", reason: "a function, which only Emacs can run", source: source))
581 continue
582 }
583 guard key.allSatisfy({ $0.isLetter || $0.isNumber || $0 == "_" || $0 == "-" }) else {
584 unsupported.append(Note(id: id(), name: "Denote template \(key)", reason: "config.toml keys are letters, digits, _ and -", source: source))
585 continue
586 }
587 items.removeAll { if case .denoteTemplate(key, _) = $0.change { true } else { false } }
588 items.append(Item(id: id(), name: "Denote template \(key)", summary: "denote-templates.\(key) = \(UserConfig.format(.string(text)).prefix(60))",
589 source: source, change: .denoteTemplate(key: key, text: text)))
590 }
567 case "org-roam-directory", "org-roam-dailies-directory": 591 case "org-roam-directory", "org-roam-dailies-directory":
568 guard let dir = value.string else { return note("not a string") } 592 guard let dir = value.string else { return note("not a string") }
569 add(name, .string(dir)) 593 add(name, .string(dir))
@@ -1134,7 +1158,15 @@ extension EmacsImport {
1134 blocks += 1 1158 blocks += 1
1135 } 1159 }
1136 if blocks > 0 { UserConfig.setStructureTemplates(rows, in: defaults) } 1160 if blocks > 0 { UserConfig.setStructureTemplates(rows, in: defaults) }
1137 if writeConfig, settings + blocks > 0 { 1161 var notes = UserConfig.denoteTemplates(defaults), noteTemplates = 0
1162 for item in items {
1163 guard case .denoteTemplate(let key, let text) = item.change else { continue }
1164 notes.removeAll { $0.key == key }
1165 notes.append((key, text))
1166 noteTemplates += 1
1167 }
1168 if noteTemplates > 0 { UserConfig.setDenoteTemplates(notes, in: defaults) }
1169 if writeConfig, settings + blocks + noteTemplates > 0 {
1138 var text = (try? String(contentsOf: configFile, encoding: .utf8)) ?? "" 1170 var text = (try? String(contentsOf: configFile, encoding: .utf8)) ?? ""
1139 for setting in stored { 1171 for setting in stored {
1140 text = UserConfig.setting(text, section: setting.section, key: setting.key, to: UserConfig.value(setting, in: defaults)) 1172 text = UserConfig.setting(text, section: setting.section, key: setting.key, to: UserConfig.value(setting, in: defaults))
@@ -1143,11 +1175,15 @@ extension EmacsImport {
1143 guard case .structureTemplate(let key, let type) = item.change else { continue } 1175 guard case .structureTemplate(let key, let type) = item.change else { continue }
1144 text = UserConfig.setting(text, section: UserConfig.structureTemplateTable, key: key, to: .string(type)) 1176 text = UserConfig.setting(text, section: UserConfig.structureTemplateTable, key: key, to: .string(type))
1145 } 1177 }
1178 for item in items {
1179 guard case .denoteTemplate(let key, let template) = item.change else { continue }
1180 text = UserConfig.setting(text, section: UserConfig.denoteTemplateTable, key: key, to: .string(template))
1181 }
1146 try? text.write(to: configFile, atomically: true, encoding: .utf8) 1182 try? text.write(to: configFile, atomically: true, encoding: .utf8)
1147 } 1183 }
1148 func count(_ n: Int, _ word: String) -> String? { n == 0 ? nil : "\(n) \(word)\(n == 1 ? "" : "s")" } 1184 func count(_ n: Int, _ word: String) -> String? { n == 0 ? nil : "\(n) \(word)\(n == 1 ? "" : "s")" }
1149 let done = [count(settings, "setting"), count(folders, "folder"), count(templates, "capture template"), count(bindings, "key binding"), 1185 let done = [count(settings, "setting"), count(folders, "folder"), count(templates, "capture template"), count(bindings, "key binding"),
1150 count(blocks, "structure template"), count(views, "agenda view"), count(projects, "publishing project")].compactMap { $0 } 1186 count(blocks, "structure template"), count(noteTemplates, "Denote template"), count(views, "agenda view"), count(projects, "publishing project")].compactMap { $0 }
1151 var summary = done.isEmpty ? "Nothing new to import." : "Imported " + done.joined(separator: ", ") + "." 1187 var summary = done.isEmpty ? "Nothing new to import." : "Imported " + done.joined(separator: ", ") + "."
1152 if !problems.isEmpty { summary += " " + problems.joined(separator: "; ") + "." } 1188 if !problems.isEmpty { summary += " " + problems.joined(separator: "; ") + "." }
1153 return summary 1189 return summary
Sources/OrgApp/EmacsImportSections.swift +1
@@ -9,6 +9,7 @@ extension EmacsImport {
9 ("Capture templates", items.filter { if case .capture = $0.change { true } else { false } }), 9 ("Capture templates", items.filter { if case .capture = $0.change { true } else { false } }),
10 ("Key bindings", items.filter { if case .binding = $0.change { true } else { false } }), 10 ("Key bindings", items.filter { if case .binding = $0.change { true } else { false } }),
11 ("Structure templates", items.filter { if case .structureTemplate = $0.change { true } else { false } }), 11 ("Structure templates", items.filter { if case .structureTemplate = $0.change { true } else { false } }),
12 ("Denote templates", items.filter { if case .denoteTemplate = $0.change { true } else { false } }),
12 ("Agenda views", items.filter { if case .view = $0.change { true } else { false } }), 13 ("Agenda views", items.filter { if case .view = $0.change { true } else { false } }),
13 ].filter { !$0.1.isEmpty } 14 ].filter { !$0.1.isEmpty }
14 } 15 }
Sources/OrgApp/OrgPreferences.swift +4
@@ -181,6 +181,10 @@ public enum OrgPreferences {
181 public static func denoteJournalKeyword(_ defaults: UserDefaults = .standard) -> String { string("denoteJournalKeyword", defaults).nonEmpty ?? "journal" } 181 public static func denoteJournalKeyword(_ defaults: UserDefaults = .standard) -> String { string("denoteJournalKeyword", defaults).nonEmpty ?? "journal" }
182 /// `denote-journal-title-format`, a `format-time-string` format. 182 /// `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" } 183 public static func denoteJournalTitle(_ defaults: UserDefaults = .standard) -> String { string("denoteJournalTitle", defaults).nonEmpty ?? "%A %-e %B %Y %H:%M" }
184 /// `denote-prompts`: what a new note asks after its title, in order.
185 public static func denotePrompts(_ defaults: UserDefaults = .standard) -> [String] {
186 string("denotePrompts", defaults).split(whereSeparator: \.isWhitespace).map(String.init)
187 }
184 /// `org-attach-id-dir`, relative to an org file's folder unless absolute. 188 /// `org-attach-id-dir`, relative to an org file's folder unless absolute.
185 public static func attachIDDir(_ defaults: UserDefaults = .standard) -> String { 189 public static func attachIDDir(_ defaults: UserDefaults = .standard) -> String {
186 let dir = string("attachIDDir", defaults) 190 let dir = string("attachIDDir", defaults)
Sources/OrgApp/RoamActions.swift +76 −15
@@ -41,6 +41,16 @@ public struct RoamActions {
41 private var denote: Bool { OrgPreferences.usesDenote() } 41 private var denote: Bool { OrgPreferences.usesDenote() }
42 private var linkType: String { denote ? "denote:" : "id:" } 42 private var linkType: String { denote ? "denote:" : "id:" }
43 43
44 /// A date prompt's answer, read by `org-read-date`. Without a time, the time of day stays
45 /// now's, as `org-read-date` with `to-time` keeps it.
46 nonisolated static func date(_ answer: String, now: Date = Date()) -> Date? {
47 let read = ReadDate.read(answer, default: nil, now: now, calendar: .current)
48 guard let chosen = Calendar.current.date(from: read.components(.current)) else { return nil }
49 let time = Calendar.current.dateComponents([.hour, .minute, .second], from: now)
50 return Calendar.current.date(bySettingHour: read.timeGiven ? read.hour : time.hour!, minute: read.timeGiven ? read.minute : time.minute!,
51 second: read.timeGiven ? 0 : time.second!, of: chosen) ?? chosen
52 }
53
44 private func day(_ offset: Int, from now: Date = Date()) -> Date { 54 private func day(_ offset: Int, from now: Date = Date()) -> Date {
45 Calendar.current.date(byAdding: .day, value: offset, to: now) ?? now 55 Calendar.current.date(byAdding: .day, value: offset, to: now) ?? now
46 } 56 }
@@ -56,14 +66,7 @@ public struct RoamActions {
56 case "app.dailies.date", "app.dailies.capture-date": 66 case "app.dailies.date", "app.dailies.capture-date":
57 let goto = id == "app.dailies.date" 67 let goto = id == "app.dailies.date"
58 ask(Prompt(key: "date", message: goto ? "Find daily-note: " : "Capture to daily-note: ", date: Prompt.DateRead(defaultDate: nil))) { answer in 68 ask(Prompt(key: "date", message: goto ? "Find daily-note: " : "Capture to daily-note: ", date: Prompt.DateRead(defaultDate: nil))) { answer in
59 guard let answer else { return } 69 guard let answer, let date = Self.date(answer) else { return }
60 let now = Date()
61 let read = ReadDate.read(answer, default: nil, now: now, calendar: .current)
62 guard let chosen = Calendar.current.date(from: read.components(.current)) else { return }
63 // The time of day stays now's, as `org-read-date` with `to-time` keeps it.
64 let time = Calendar.current.dateComponents([.hour, .minute, .second], from: now)
65 let date = Calendar.current.date(bySettingHour: read.timeGiven ? read.hour : time.hour!, minute: read.timeGiven ? read.minute : time.minute!,
66 second: read.timeGiven ? 0 : time.second!, of: chosen) ?? chosen
67 if goto { self.goto(date) } else { capture(date) } 70 if goto { self.goto(date) } else { capture(date) }
68 } 71 }
69 case "app.dailies.next", "app.dailies.previous": 72 case "app.dailies.next", "app.dailies.previous":
@@ -177,21 +180,79 @@ public struct RoamActions {
177 } 180 }
178 } 181 }
179 182
180 /// `denote`: the keywords, separated by commas or spaces, then the note in 183 /// What a new Denote note's questions give.
181 /// `denote-directory`. The keywords already in file names are offered. 184 struct DenoteAnswers {
185 var keywords: [String] = []
186 var folder: String?
187 var date: Date?
188 var template = ""
189 var signature = ""
190 }
191
192 /// `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.
182 private func createDenote(_ title: String, known: [IndexStore.Node], _ then: @escaping (NodeChoice) -> Void) { 194 private func createDenote(_ title: String, known: [IndexStore.Node], _ then: @escaping (NodeChoice) -> Void) {
183 let keywords = Denote.keywords(known.flatMap { Denote.name(ofFile: $0.location.path).keywords }) 195 guard let root = DenoteNote.directory(roots: roots()) else { return show("No folder for new notes") }
184 ask(Prompt(key: "keywords", message: "New file KEYWORDS: ", choices: keywords, requireMatch: false)) { answer in 196 createDenote(title, root: root, prompts: OrgPreferences.denotePrompts(), templates: UserConfig.denoteTemplates(.standard),
185 guard let answer else { return } 197 keywords: Denote.keywords(known.flatMap { Denote.name(ofFile: $0.location.path).keywords }), then)
186 guard let folder = DenoteNote.directory(roots: roots()) else { return show("No folder for new notes") } 198 }
199
200 func createDenote(
201 _ title: String, root: String, prompts: [String], templates: [(key: String, text: String)], keywords: [String],
202 answers: DenoteAnswers = DenoteAnswers(), _ then: @escaping (NodeChoice) -> Void
203 ) {
204 func next(_ answers: DenoteAnswers) {
205 createDenote(title, root: root, prompts: Array(prompts.dropFirst()), templates: templates, keywords: keywords, answers: answers, then)
206 }
207 var answers = answers
208 switch prompts.first {
209 case nil:
187 do { 210 do {
188 let note = try DenoteNote.create(title: title, keywords: answer.split(whereSeparator: { $0 == "," || $0.isWhitespace }).map(String.init), in: folder) 211 let note = try DenoteNote.create(title: title, keywords: answers.keywords, in: answers.folder ?? root, root: root,
212 now: answers.date ?? Date(), signature: answers.signature, template: answers.template)
189 refresh() 213 refresh()
190 show("Created \((note.path as NSString).lastPathComponent)") 214 show("Created \((note.path as NSString).lastPathComponent)")
191 then(.created(path: note.path, id: note.id, title: title)) 215 then(.created(path: note.path, id: note.id, title: title))
192 } catch { 216 } catch {
193 show("Can't make the note: \(error)") 217 show("Can't make the note: \(error)")
194 } 218 }
219 case "keywords":
220 // Separated by commas or spaces; the keywords already in file names are offered.
221 ask(Prompt(key: "keywords", message: "New file KEYWORDS: ", choices: keywords, requireMatch: false)) { answer in
222 guard let answer else { return }
223 answers.keywords = answer.split(whereSeparator: { $0 == "," || $0.isWhitespace }).map(String.init)
224 next(answers)
225 }
226 case "subdirectory":
227 let folders = DenoteNote.subdirectories(of: root)
228 guard !folders.isEmpty else { return next(answers) }
229 ask(Prompt(key: "subdirectory", message: "Select SUBDIRECTORY: ", choices: ["."] + folders)) { answer in
230 guard let answer else { return }
231 answers.folder = answer == "." || answer.isEmpty ? root : (root as NSString).appendingPathComponent(answer)
232 next(answers)
233 }
234 case "date":
235 ask(Prompt(key: "date", message: "DATE and TIME for note: ", date: Prompt.DateRead(defaultDate: nil))) { answer in
236 guard let answer else { return }
237 answers.date = Self.date(answer)
238 next(answers)
239 }
240 case "template":
241 guard !templates.isEmpty else { return next(answers) }
242 ask(Prompt(key: "template", message: "Select TEMPLATE key: ", choices: templates.map(\.key))) { answer in
243 guard let answer else { return }
244 answers.template = templates.first { $0.key == answer }?.text ?? ""
245 next(answers)
246 }
247 case "signature":
248 ask(Prompt(key: "signature", message: "New file SIGNATURE: ", requireMatch: false)) { answer in
249 guard let answer else { return }
250 answers.signature = answer
251 next(answers)
252 }
253 default:
254 // The title is asked first anyway; Org is the only file type; the rest have no equal.
255 next(answers)
195 } 256 }
196 } 257 }
197 258
Sources/OrgApp/UserConfig.swift +33
@@ -183,6 +183,8 @@ public enum UserConfig {
183 comment: "the folder denote-journal entries are in, relative to denote-directory", legacy: ""), 183 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"), 184 Setting(section: "", key: "denote-journal-keyword", defaultsKey: "denoteJournalKeyword", kind: .string, fallback: .string("journal"),
185 comment: "the keyword journal entries have", legacy: ""), 185 comment: "the keyword journal entries have", legacy: ""),
186 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: ""),
186 Setting(section: "", key: "denote-journal-title-format", defaultsKey: "denoteJournalTitle", kind: .string, fallback: .string("%A %-e %B %Y %H:%M"), 188 Setting(section: "", key: "denote-journal-title-format", defaultsKey: "denoteJournalTitle", kind: .string, fallback: .string("%A %-e %B %Y %H:%M"),
187 comment: "a journal entry's title; a format-time-string format", legacy: ""), 189 comment: "a journal entry's title; a format-time-string format", legacy: ""),
188 Setting(section: "", key: "auto-fill-mode", defaultsKey: "autoFill", kind: .bool, fallback: .bool(false), 190 Setting(section: "", key: "auto-fill-mode", defaultsKey: "autoFill", kind: .bool, fallback: .bool(false),
@@ -450,7 +452,22 @@ public enum UserConfig {
450 } 452 }
451 let templates = tables.first { $0.name == structureTemplateTable } 453 let templates = tables.first { $0.name == structureTemplateTable }
452 if templates == nil, defaults.object(forKey: structureTemplatesKey) != nil { defaults.removeObject(forKey: structureTemplatesKey) } 454 if templates == nil, defaults.object(forKey: structureTemplatesKey) != nil { defaults.removeObject(forKey: structureTemplatesKey) }
455 if !tables.contains(where: { $0.name == denoteTemplateTable }), defaults.object(forKey: denoteTemplatesKey) != nil {
456 defaults.removeObject(forKey: denoteTemplatesKey)
457 }
453 for table in tables { 458 for table in tables {
459 if table.name == denoteTemplateTable {
460 var rows: [String] = []
461 for key in table.keys {
462 guard let text = table.values[key]?.string else {
463 problems.append("config.toml: \(denoteTemplateTable).\(key) must be text")
464 continue
465 }
466 rows.append(key + "\t" + text)
467 }
468 if defaults.stringArray(forKey: denoteTemplatesKey) != rows { defaults.set(rows, forKey: denoteTemplatesKey) }
469 continue
470 }
454 if table.name == structureTemplateTable { 471 if table.name == structureTemplateTable {
455 var rows: [String] = [] 472 var rows: [String] = []
456 for key in table.keys { 473 for key in table.keys {
@@ -497,6 +514,22 @@ public enum UserConfig {
497 defaults.set(templates.map { $0.key + "\t" + $0.type }, forKey: structureTemplatesKey) 514 defaults.set(templates.map { $0.key + "\t" + $0.type }, forKey: structureTemplatesKey)
498 } 515 }
499 516
517 /// `[denote-templates]`, `denote-templates`: `key = "text"`, the text a new note starts
518 /// with after its front matter. Kept in user defaults as `key<Tab>text`.
519 public static let denoteTemplateTable = "denote-templates"
520 static let denoteTemplatesKey = "denoteTemplates"
521
522 public static func denoteTemplates(_ defaults: UserDefaults) -> [(key: String, text: String)] {
523 (defaults.stringArray(forKey: denoteTemplatesKey) ?? []).compactMap { row in
524 guard let tab = row.firstIndex(of: "\t") else { return nil }
525 return (String(row[..<tab]), String(row[row.index(after: tab)...]))
526 }
527 }
528
529 public static func setDenoteTemplates(_ templates: [(key: String, text: String)], in defaults: UserDefaults) {
530 defaults.set(templates.map { $0.key + "\t" + $0.text }, forKey: denoteTemplatesKey)
531 }
532
500 static func path(_ section: String, _ key: String) -> String { section.isEmpty ? key : section + "." + key } 533 static func path(_ section: String, _ key: String) -> String { section.isEmpty ? key : section + "." + key }
501 534
502 /// Whether the file uses names from before settings took Emacs's names. 535 /// Whether the file uses names from before settings took Emacs's names.
Sources/OrgCore/Links/Denote.swift +5 −10
@@ -87,20 +87,15 @@ public enum Denote {
87 return name + "." + ext 87 return name + "." + ext
88 } 88 }
89 89
90 /// `denote-org-front-matter`, dated as an inactive Org timestamp. 90 /// `denote-org-front-matter`, dated as an inactive Org timestamp. The signature line is
91 public static func frontMatter(title: String, date: Date, keywords: [String], identifier: String, calendar: Calendar = .current) -> String { 91 /// 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 {
92 let c = calendar.dateComponents([.year, .month, .day, .weekday, .hour, .minute], from: date) 93 let c = calendar.dateComponents([.year, .month, .day, .weekday, .hour, .minute], from: date)
93 let day = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"][c.weekday! - 1] 94 let day = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"][c.weekday! - 1]
94 let stamp = String(format: "[%04d-%02d-%02d %@ %02d:%02d]", c.year!, c.month!, c.day!, day, c.hour!, c.minute!) 95 let stamp = String(format: "[%04d-%02d-%02d %@ %02d:%02d]", c.year!, c.month!, c.day!, day, c.hour!, c.minute!)
95 let tags = keywords.isEmpty ? "" : ":" + keywords.joined(separator: ":") + ":" 96 let tags = keywords.isEmpty ? "" : ":" + keywords.joined(separator: ":") + ":"
96 return """ 97 return "#+title: \(title)\n#+date: \(stamp)\n#+filetags: \(tags)\n#+identifier: \(identifier)\n"
97 #+title: \(title) 98 + (signature.isEmpty ? "" : "#+signature: \(signature)\n") + "\n"
98 #+date: \(stamp)
99 #+filetags: \(tags)
100 #+identifier: \(identifier)
101
102
103 """
104 } 99 }
105 100
106 // MARK: - Reading names and front matter 101 // MARK: - Reading names and front matter
Tests/OrgAppTests/DailiesTests.swift +31 −1
@@ -78,7 +78,37 @@ struct DailiesTests {
78 let note = try DenoteNote.create(title: "Field Notes", keywords: ["Work", "ideas"], in: folder, now: Self.day) 78 let note = try DenoteNote.create(title: "Field Notes", keywords: ["Work", "ideas"], in: folder, now: Self.day)
79 #expect((note.path as NSString).lastPathComponent == "20261011T120000--field-notes__ideas_work.org" && note.id == "20261011T120000") 79 #expect((note.path as NSString).lastPathComponent == "20261011T120000--field-notes__ideas_work.org" && note.id == "20261011T120000")
80 #expect(try String(contentsOfFile: note.path, encoding: .utf8).hasPrefix("#+title: Field Notes\n")) 80 #expect(try String(contentsOfFile: note.path, encoding: .utf8).hasPrefix("#+title: Field Notes\n"))
81 #expect(throws: (any Error).self) { try DenoteNote.create(title: "Field Notes", keywords: ["work", "ideas"], in: folder, now: Self.day) } 81 // The same second again under the folder: the next unused one, the date unchanged.
82 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")
84 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")
86 #expect((other.path as NSString).lastPathComponent == "20261011T120002==two=words--plan.org")
87 #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")
89 #expect(DenoteNote.subdirectories(of: folder) == ["projects"])
90 }
91
92 /// `denote-prompts` sets the questions after the title and their order.
93 @MainActor
94 @Test func denotePromptsInOrder() throws {
95 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-denote-\(UUID().uuidString)").resolvingSymlinksInPath()
96 defer { try? FileManager.default.removeItem(at: folder) }
97 try FileManager.default.createDirectory(at: folder.appendingPathComponent("work"), withIntermediateDirectories: true)
98 var asked: [String] = []
99 let answers = ["signature": "a1", "subdirectory": "work", "date": "2026-10-11 09:30", "template": "memo", "keywords": "beta, alpha"]
100 var created: String?
101 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]) },
103 open: { _, _ in }, insertLink: { _, _ in }, refresh: {})
104 actions.createDenote("Field Notes", root: folder.path, prompts: ["title", "signature", "subdirectory", "date", "file-type", "template", "keywords"],
105 templates: [("report", "* R\n"), ("memo", "* M\n")], keywords: []) { choice in
106 if case .created(let path, _, _) = choice { created = path }
107 }
108 #expect(asked == ["signature", "subdirectory", "date", "template", "keywords"])
109 let path = try #require(created)
110 #expect(path == folder.appendingPathComponent("work/20261011T093000==a1--field-notes__alpha_beta.org").path)
111 #expect(try String(contentsOfFile: path, encoding: .utf8).hasSuffix("#+signature: a1\n\n* M\n"))
82 } 112 }
83 113
84 @MainActor 114 @MainActor
Tests/OrgAppTests/DenoteOracleTests.swift +29
@@ -92,4 +92,33 @@ struct DenoteOracleTests {
92 == String(contentsOf: theirs.appendingPathComponent(name), encoding: .utf8), "\(name)") 92 == String(contentsOf: theirs.appendingPathComponent(name), encoding: .utf8), "\(name)")
93 } 93 }
94 } 94 }
95
96 /// A note in a subfolder with a signature and a template, dated a second some file's
97 /// identifier already has.
98 @Test(.enabled(if: enabled)) func optionsMatchDenote() throws {
99 let theirs = try Self.folder(), ours = try Self.folder()
100 defer { try? FileManager.default.removeItem(at: theirs); try? FileManager.default.removeItem(at: ours) }
101 let taken = "20261011T093000--taken.org"
102 for dir in [theirs, ours] {
103 try FileManager.default.createDirectory(at: dir.appendingPathComponent("work"), withIntermediateDirectories: true)
104 try "x\n".write(to: dir.appendingPathComponent(taken), atomically: true, encoding: .utf8)
105 }
106 let template = "* Goals\n\n* Notes\n"
107 try Self.denote(theirs, """
108 (let ((denote-templates '((plan . \(template.debugDescription)))))
109 (denote "Q4 Plan: draft" (denote-keywords-sort (list "work" "ideas")) 'org \(theirs.appendingPathComponent("work/").path.debugDescription)
110 "2026-10-11 09:30" 'plan "Part One")
111 (save-buffer))
112 """)
113 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,
115 now: date, signature: "Part One", template: template)
116 let names = try FileManager.default.contentsOfDirectory(atPath: theirs.appendingPathComponent("work").path)
117 #expect(names.count == 1)
118 #expect(try FileManager.default.contentsOfDirectory(atPath: ours.appendingPathComponent("work").path) == names)
119 for name in names {
120 #expect(try String(contentsOf: ours.appendingPathComponent("work/" + name), encoding: .utf8)
121 == String(contentsOf: theirs.appendingPathComponent("work/" + name), encoding: .utf8), "\(name)")
122 }
123 }
95} 124}
Tests/OrgAppTests/EmacsImportTests.swift +34
@@ -280,6 +280,40 @@ struct EmacsImportTests {
280 #expect(s["denote-journal-title-format"] == .string("%A %-e %B %Y %H:%M")) 280 #expect(s["denote-journal-title-format"] == .string("%A %-e %B %Y %H:%M"))
281 } 281 }
282 282
283 @MainActor
284 @Test func importsDenotePromptsAndTemplates() async throws {
285 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-import-\(UUID().uuidString)")
286 try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
287 defer { try? FileManager.default.removeItem(at: folder) }
288 try #"""
289 (setq denote-prompts '(title keywords subdirectory signature))
290 (setq denote-templates
291 `((report . "* Summary\n\n* Details\n")
292 (memo . ,(concat "* To" "\n\n" "* From\n"))
293 (journal . my-denote-journal-template)))
294 """#.write(to: folder.appendingPathComponent("init.el"), atomically: true, encoding: .utf8)
295 let result = EmacsImport.scan(EmacsImport.files(in: folder))
296 #expect(settings(result)["denote-prompts"] == .string("title keywords subdirectory signature"))
297 let templates = result.items.compactMap { item -> String? in
298 if case .denoteTemplate(let key, let text) = item.change { "\(key)=\(text)" } else { nil }
299 }
300 #expect(templates == ["report=* Summary\n\n* Details\n", "memo=* To\n\n* From\n"])
301 #expect(result.unsupported.map(\.name) == ["Denote template journal"])
302
303 let name = "orgstar-import-\(UUID().uuidString)"
304 let defaults = UserDefaults(suiteName: name)!
305 defer { defaults.removePersistentDomain(forName: name) }
306 _ = await EmacsImport.apply(result.items, defaults: defaults, workspace: nil, directory: folder, writeConfig: true)
307 #expect(UserConfig.denoteTemplates(defaults).map(\.key) == ["report", "memo"])
308 #expect(OrgPreferences.denotePrompts(defaults) == ["title", "keywords", "subdirectory", "signature"])
309 let config = try String(contentsOf: folder.appendingPathComponent("config.toml"), encoding: .utf8)
310 // The file reads back to the same templates.
311 let reread = UserDefaults(suiteName: name + "-reread")!
312 defer { reread.removePersistentDomain(forName: name + "-reread") }
313 #expect(UserConfig.apply(config, to: reread).isEmpty, "\(config)")
314 #expect(UserConfig.denoteTemplates(reread).map(\.text) == ["* Summary\n\n* Details\n", "* To\n\n* From\n"])
315 }
316
283 @Test func readsPublishingProjects() async throws { 317 @Test func readsPublishingProjects() async throws {
284 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-import-\(UUID().uuidString)") 318 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-import-\(UUID().uuidString)")
285 try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true) 319 try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
Tests/OrgCoreTests/DenoteTests.swift +7
@@ -45,6 +45,13 @@ struct DenoteTests {
45 """) 45 """)
46 } 46 }
47 47
48 @Test func signatures() {
49 #expect(Denote.signature("Two Words") == "two=words")
50 #expect(Denote.signature(" 1a_b-c==d ") == "1a=bc=d")
51 #expect(Denote.frontMatter(title: "A", date: Self.date, keywords: [], identifier: "20261119T090503", signature: "1a", calendar: Self.calendar)
52 == "#+title: A\n#+date: [2026-11-19 Thu 09:05]\n#+filetags: \n#+identifier: 20261119T090503\n#+signature: 1a\n\n")
53 }
54
48 @Test func readsNamesInAnyOrder() { 55 @Test func readsNamesInAnyOrder() {
49 #expect(Denote.name(ofFile: "/n/20261119T090503==1a--a-note__kw1_kw2.org") 56 #expect(Denote.name(ofFile: "/n/20261119T090503==1a--a-note__kw1_kw2.org")
50 == Denote.Name(identifier: "20261119T090503", signature: "1a", title: "a-note", keywords: ["kw1", "kw2"], ext: "org")) 57 == Denote.Name(identifier: "20261119T090503", signature: "1a", title: "a-note", keywords: ["kw1", "kw2"], ext: "org"))
docs/manual/guide/09-links.org +19 −6
@@ -342,9 +342,21 @@ With =notes-package = "denote"= in =config.toml=, the same commands follow Denot
342- Find Node… and Insert Node Link… list the Org files whose names have a Denote 342- Find Node… and Insert Node Link… list the Org files whose names have a Denote
343 identifier, titled by their =#+title:=, and Insert Node Link… inserts 343 identifier, titled by their =#+title:=, and Insert Node Link… inserts
344 =[[denote:…][Title]]=. 344 =[[denote:…][Title]]=.
345- A title no note has asks for keywords, separated by commas or spaces, offering the 345- A title no note has makes a note in =denote-directory= (the first folder unless set),
346 keywords in existing file names, then makes the note in =denote-directory= (the first 346 after the questions =denote-prompts= lists, in its order. The default is
347 folder unless set), as =denote= does with its default prompts: 347 ="title keywords"=; the title is always the one typed.
348 - =keywords=: separated by commas or spaces, offering the keywords in existing file
349 names.
350 - =subdirectory=: a folder under =denote-directory= (=.= for itself) to put the note in.
351 - =date=: the note's date, read as =org-read-date= reads one; without a time, the time
352 is now's.
353 - =template=: a key of =[denote-templates]=, whose text goes after the front matter.
354 - =signature=: put in the name after ~==~, in lower case with ~=~ between words, and
355 in a =#+signature:= line.
356
357 =file-type= and =identifier= are not asked: notes are Org, and the identifier is the
358 date's, or the first second after it no file under =denote-directory= has. With the
359 default prompts:
348 360
349 #+BEGIN_SRC org 361 #+BEGIN_SRC org
350 ,#+title: Field Notes 362 ,#+title: Field Notes
@@ -366,9 +378,10 @@ With =notes-package = "denote"= in =config.toml=, the same commands follow Denot
366 the name, and the keywords keep their order. Links keep working, as they use the 378 the name, and the keywords keep their order. Links keep working, as they use the
367 identifier. 379 identifier.
368 380
369Import from Emacs reads =denote-directory=, =denote-journal-directory=, 381Import from Emacs reads =denote-directory=, =denote-prompts=, =denote-templates=,
370=denote-journal-keyword= and =denote-journal-title-format=. Denote notes in Markdown or 382=denote-journal-directory=, =denote-journal-keyword= and =denote-journal-title-format=.
371plain text are not supported. 383Templates that are functions, and Denote notes in Markdown or plain text, are not
384supported.
372 385
373* Inline images 386* Inline images
374 387
docs/manual/guide/13-configuration.org +16 −1
@@ -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-journal-directory=, =denote-journal-keyword=, =denote-journal-title-format= | | 182| =notes-package=, =denote-directory=, =denote-prompts=, =denote-journal-directory=, =denote-journal-keyword=, =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= | |
@@ -241,6 +241,7 @@ A key you remove from the file goes back to its default. A key that isn't in the
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 folder new Denote notes go in; empty for the first sidebar folder. Mirrors =denote-directory=. |
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=. |
244| =denote-journal-directory= | string | ="journal"= | The folder journal entries are in, relative to =denote-directory=. Mirrors =denote-journal-directory=. | 245| =denote-journal-directory= | string | ="journal"= | The folder journal entries are in, relative to =denote-directory=. Mirrors =denote-journal-directory=. |
245| =denote-journal-keyword= | string | ="journal"= | The keyword journal entries have. Mirrors =denote-journal-keyword=. | 246| =denote-journal-keyword= | string | ="journal"= | The keyword journal entries have. Mirrors =denote-journal-keyword=. |
246| =denote-journal-title-format= | string | ="%A %-e %B %Y %H:%M"= | A new journal entry's title, a =format-time-string= format. | 247| =denote-journal-title-format= | string | ="%A %-e %B %Y %H:%M"= | A new journal entry's title, a =format-time-string= format. |
@@ -363,6 +364,18 @@ py = "src python"
363 364
364Keys are letters, digits, =_= and =-=. Without the table, Org's templates apply. Emacs import adds entries here and so does nothing else in the app; remove one by deleting its line. 365Keys are letters, digits, =_= and =-=. Without the table, Org's templates apply. Emacs import adds entries here and so does nothing else in the app; remove one by deleting its line.
365 366
367** [denote-templates]
368
369Text a new Denote note starts with after its front matter, chosen by key when =denote-prompts= has =template=. Mirrors =denote-templates=.
370
371#+BEGIN_SRC toml
372[denote-templates]
373report = "* Summary\n\n* Details\n"
374memo = "* To\n\n* From\n"
375#+END_SRC
376
377Keys are letters, digits, =_= and =-=. Emacs import adds entries here; remove one by deleting its line.
378
366** [[publish]] 379** [[publish]]
367 380
368Publishing projects, one table each, as =org-publish-project-alist= has them. They're read when you publish; see [[file:12-export.org::*Publishing][Publishing]] for the keys. The Settings window leaves them as they are. 381Publishing projects, one table each, as =org-publish-project-alist= has them. They're read when you publish; see [[file:12-export.org::*Publishing][Publishing]] for the keys. The Settings window leaves them as they are.
@@ -624,6 +637,8 @@ Only variables whose names start with =org-=, =appt-=, =display-line-numbers=, =
624| =org-track-ordered-property-with-tag= | A tag name as given; =t= becomes ="t"=, =nil= ="nil"= | 637| =org-track-ordered-property-with-tag= | A tag name as given; =t= becomes ="t"=, =nil= ="nil"= |
625| =org-roam-directory=, =org-roam-dailies-directory= | The same keys, when the value is a string or a form that makes one | 638| =org-roam-directory=, =org-roam-dailies-directory= | The same keys, when the value is a string or a form that makes one |
626| =denote-directory=, =denote-journal-directory=, =denote-journal-keyword= | The same keys, when the value is a string | 639| =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 |
641| =denote-templates= | =[denote-templates]=: entries whose text is a string or =concat= of strings; a function is listed as unsupported |
627| =denote-journal-title-format= | The same key; the symbols =day-date-month-year=, =-24h= and =-12h= become their formats | 642| =denote-journal-title-format= | The same key; the symbols =day-date-month-year=, =-24h= and =-12h= become their formats |
628| =org-roam-dailies-capture-templates= | =org-roam-dailies-file=, =-head= and =-entry=, from the first template's =(file+head NAME HEAD)= target and template | 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 |
629| =org-timer-format=, =org-timer-default-timer= | The same keys; a number becomes a string | 644| =org-timer-format=, =org-timer-default-timer= | The same keys; a number becomes a string |