Denote prompts, templates, signatures and dates !388

merged merged by cmc on 2026-11-19 20:32 UTC · krz/orgstar:denote-prompts into main

14 files changed, +332 −43

Layout: unified · split

Sources/OrgApp/ConfigSync.swift +3
@@ -141,6 +141,9 @@ public final class ConfigSync {
141141 for template in UserConfig.structureTemplates(defaults) where values[UserConfig.path(UserConfig.structureTemplateTable, template.key)] != .string(template.type) {
142142 current = UserConfig.setting(current, section: UserConfig.structureTemplateTable, key: template.key, to: .string(template.type))
143143 }
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 }
144147 guard current != original else { return }
145148 text = current
146149 try? current.write(to: target, atomically: true, encoding: .utf8)
Sources/OrgApp/DenoteNote.swift +36 −8
@@ -1,9 +1,9 @@
11import Foundation
22import OrgCore
33
4/// A new Denote note, as `denote` makes it with the default `denote-prompts` (title and
5/// keywords): `IDENTIFIER--title__keywords.org` in `denote-directory`, starting with the
6/// Org front matter.
4/// A new Denote note, as `denote` makes it: `IDENTIFIER==signature--title__keywords.org` in
5/// `denote-directory` or a folder under it, starting with the Org front matter and then the
6/// template.
77public enum DenoteNote {
88 /// `denote-directory`: the setting, else the first folder.
99 public static func directory(roots: [String], defaults: UserDefaults = .standard) -> String? {
@@ -11,15 +11,43 @@ public enum DenoteNote {
1111 return denote.isEmpty ? roots.first : OrgAttach.expand(denote, in: roots.first ?? NSHomeDirectory())
1212 }
1313
14 /// Makes the note's file in `folder`. Fails rather than replace a file that's there.
15 public static func create(title: String, keywords: [String], in folder: String, now: Date = Date()) throws -> (path: String, id: String) {
16 let id = Denote.identifier(for: now)
14 /// `denote-directory-subdirectories`: the folders under `root`, relative to it, without
15 /// hidden ones.
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)
1744 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)
1947 let path = (folder as NSString).appendingPathComponent(name)
2048 try FileManager.default.createDirectory(atPath: folder, withIntermediateDirectories: true)
2149 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
2351 try Data(text.utf8).write(to: URL(fileURLWithPath: path), options: .withoutOverwriting)
2452 return (path, id)
2553 }
Sources/OrgApp/EmacsImport.swift +38 −2
@@ -21,6 +21,8 @@ public struct EmacsImport: Sendable {
2121 case view(name: String, toml: String)
2222 /// A `[[publish]]` table for config.toml.
2323 case publish(name: String, toml: String)
24 /// A `[denote-templates]` entry for config.toml.
25 case denoteTemplate(key: String, text: String)
2426 }
2527
2628 public struct Item: Sendable, Identifiable {
@@ -564,6 +566,28 @@ public struct EmacsImport: Sendable {
564566 let formats = ["day-date-month-year": "%A %-e %B %Y", "day-date-month-year-24h": "%A %-e %B %Y %H:%M",
565567 "day-date-month-year-12h": "%A %-e %B %Y %I:%M %p", "day": "%A"]
566568 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 }
567591 case "org-roam-directory", "org-roam-dailies-directory":
568592 guard let dir = value.string else { return note("not a string") }
569593 add(name, .string(dir))
@@ -1134,7 +1158,15 @@ extension EmacsImport {
11341158 blocks += 1
11351159 }
11361160 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 {
11381170 var text = (try? String(contentsOf: configFile, encoding: .utf8)) ?? ""
11391171 for setting in stored {
11401172 text = UserConfig.setting(text, section: setting.section, key: setting.key, to: UserConfig.value(setting, in: defaults))
@@ -1143,11 +1175,15 @@ extension EmacsImport {
11431175 guard case .structureTemplate(let key, let type) = item.change else { continue }
11441176 text = UserConfig.setting(text, section: UserConfig.structureTemplateTable, key: key, to: .string(type))
11451177 }
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 }
11461182 try? text.write(to: configFile, atomically: true, encoding: .utf8)
11471183 }
11481184 func count(_ n: Int, _ word: String) -> String? { n == 0 ? nil : "\(n) \(word)\(n == 1 ? "" : "s")" }
11491185 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 }
11511187 var summary = done.isEmpty ? "Nothing new to import." : "Imported " + done.joined(separator: ", ") + "."
11521188 if !problems.isEmpty { summary += " " + problems.joined(separator: "; ") + "." }
11531189 return summary
Sources/OrgApp/EmacsImportSections.swift +1
@@ -9,6 +9,7 @@ extension EmacsImport {
99 ("Capture templates", items.filter { if case .capture = $0.change { true } else { false } }),
1010 ("Key bindings", items.filter { if case .binding = $0.change { true } else { false } }),
1111 ("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 } }),
1213 ("Agenda views", items.filter { if case .view = $0.change { true } else { false } }),
1314 ].filter { !$0.1.isEmpty }
1415 }
Sources/OrgApp/OrgPreferences.swift +4
@@ -181,6 +181,10 @@ public enum OrgPreferences {
181181 public static func denoteJournalKeyword(_ defaults: UserDefaults = .standard) -> String { string("denoteJournalKeyword", defaults).nonEmpty ?? "journal" }
182182 /// `denote-journal-title-format`, a `format-time-string` format.
183183 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 }
184188 /// `org-attach-id-dir`, relative to an org file's folder unless absolute.
185189 public static func attachIDDir(_ defaults: UserDefaults = .standard) -> String {
186190 let dir = string("attachIDDir", defaults)
Sources/OrgApp/RoamActions.swift +76 −15
@@ -41,6 +41,16 @@ public struct RoamActions {
4141 private var denote: Bool { OrgPreferences.usesDenote() }
4242 private var linkType: String { denote ? "denote:" : "id:" }
4343
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
4454 private func day(_ offset: Int, from now: Date = Date()) -> Date {
4555 Calendar.current.date(byAdding: .day, value: offset, to: now) ?? now
4656 }
@@ -56,14 +66,7 @@ public struct RoamActions {
5666 case "app.dailies.date", "app.dailies.capture-date":
5767 let goto = id == "app.dailies.date"
5868 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 }
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
69 guard let answer, let date = Self.date(answer) else { return }
6770 if goto { self.goto(date) } else { capture(date) }
6871 }
6972 case "app.dailies.next", "app.dailies.previous":
@@ -177,21 +180,79 @@ public struct RoamActions {
177180 }
178181 }
179182
180 /// `denote`: the keywords, separated by commas or spaces, then the note in
181 /// `denote-directory`. The keywords already in file names are offered.
183 /// What a new Denote note's questions give.
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.
182194 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 })
184 ask(Prompt(key: "keywords", message: "New file KEYWORDS: ", choices: keywords, requireMatch: false)) { answer in
185 guard let answer else { return }
186 guard let folder = DenoteNote.directory(roots: roots()) else { return show("No folder for new notes") }
195 guard let root = DenoteNote.directory(roots: roots()) else { return show("No folder for new notes") }
196 createDenote(title, root: root, prompts: OrgPreferences.denotePrompts(), templates: UserConfig.denoteTemplates(.standard),
197 keywords: Denote.keywords(known.flatMap { Denote.name(ofFile: $0.location.path).keywords }), then)
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:
187210 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)
189213 refresh()
190214 show("Created \((note.path as NSString).lastPathComponent)")
191215 then(.created(path: note.path, id: note.id, title: title))
192216 } catch {
193217 show("Can't make the note: \(error)")
194218 }
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)
195256 }
196257 }
197258
Sources/OrgApp/UserConfig.swift +33
@@ -183,6 +183,8 @@ public enum UserConfig {
183183 comment: "the folder denote-journal entries are in, relative to denote-directory", legacy: ""),
184184 Setting(section: "", key: "denote-journal-keyword", defaultsKey: "denoteJournalKeyword", kind: .string, fallback: .string("journal"),
185185 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: ""),
186188 Setting(section: "", key: "denote-journal-title-format", defaultsKey: "denoteJournalTitle", kind: .string, fallback: .string("%A %-e %B %Y %H:%M"),
187189 comment: "a journal entry's title; a format-time-string format", legacy: ""),
188190 Setting(section: "", key: "auto-fill-mode", defaultsKey: "autoFill", kind: .bool, fallback: .bool(false),
@@ -450,7 +452,22 @@ public enum UserConfig {
450452 }
451453 let templates = tables.first { $0.name == structureTemplateTable }
452454 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 }
453458 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 }
454471 if table.name == structureTemplateTable {
455472 var rows: [String] = []
456473 for key in table.keys {
@@ -497,6 +514,22 @@ public enum UserConfig {
497514 defaults.set(templates.map { $0.key + "\t" + $0.type }, forKey: structureTemplatesKey)
498515 }
499516
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
500533 static func path(_ section: String, _ key: String) -> String { section.isEmpty ? key : section + "." + key }
501534
502535 /// 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 {
8787 return name + "." + ext
8888 }
8989
90 /// `denote-org-front-matter`, dated as an inactive Org timestamp.
91 public static func frontMatter(title: String, date: Date, keywords: [String], identifier: String, calendar: Calendar = .current) -> String {
90 /// `denote-org-front-matter`, dated as an inactive Org timestamp. The signature line is
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 {
9293 let c = calendar.dateComponents([.year, .month, .day, .weekday, .hour, .minute], from: date)
9394 let day = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"][c.weekday! - 1]
9495 let stamp = String(format: "[%04d-%02d-%02d %@ %02d:%02d]", c.year!, c.month!, c.day!, day, c.hour!, c.minute!)
9596 let tags = keywords.isEmpty ? "" : ":" + keywords.joined(separator: ":") + ":"
96 return """
97 #+title: \(title)
98 #+date: \(stamp)
99 #+filetags: \(tags)
100 #+identifier: \(identifier)
101
102
103 """
97 return "#+title: \(title)\n#+date: \(stamp)\n#+filetags: \(tags)\n#+identifier: \(identifier)\n"
98 + (signature.isEmpty ? "" : "#+signature: \(signature)\n") + "\n"
10499 }
105100
106101 // MARK: - Reading names and front matter
Tests/OrgAppTests/DailiesTests.swift +31 −1
@@ -78,7 +78,37 @@ struct DailiesTests {
7878 let note = try DenoteNote.create(title: "Field Notes", keywords: ["Work", "ideas"], in: folder, now: Self.day)
7979 #expect((note.path as NSString).lastPathComponent == "20261011T120000--field-notes__ideas_work.org" && note.id == "20261011T120000")
8080 #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"))
82112 }
83113
84114 @MainActor
Tests/OrgAppTests/DenoteOracleTests.swift +29
@@ -92,4 +92,33 @@ struct DenoteOracleTests {
9292 == String(contentsOf: theirs.appendingPathComponent(name), encoding: .utf8), "\(name)")
9393 }
9494 }
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 }
95124}
Tests/OrgAppTests/EmacsImportTests.swift +34
@@ -280,6 +280,40 @@ struct EmacsImportTests {
280280 #expect(s["denote-journal-title-format"] == .string("%A %-e %B %Y %H:%M"))
281281 }
282282
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
283317 @Test func readsPublishingProjects() async throws {
284318 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-import-\(UUID().uuidString)")
285319 try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
Tests/OrgCoreTests/DenoteTests.swift +7
@@ -45,6 +45,13 @@ struct DenoteTests {
4545 """)
4646 }
4747
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
4855 @Test func readsNamesInAnyOrder() {
4956 #expect(Denote.name(ofFile: "/n/20261119T090503==1a--a-note__kw1_kw2.org")
5057 == 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
342342- Find Node… and Insert Node Link… list the Org files whose names have a Denote
343343 identifier, titled by their =#+title:=, and Insert Node Link… inserts
344344 =[[denote:…][Title]]=.
345- A title no note has asks for keywords, separated by commas or spaces, offering the
346 keywords in existing file names, then makes the note in =denote-directory= (the first
347 folder unless set), as =denote= does with its default prompts:
345- A title no note has makes a note in =denote-directory= (the first folder unless set),
346 after the questions =denote-prompts= lists, in its order. The default is
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:
348360
349361 #+BEGIN_SRC org
350362 ,#+title: Field Notes
@@ -366,9 +378,10 @@ With =notes-package = "denote"= in =config.toml=, the same commands follow Denot
366378 the name, and the keywords keep their order. Links keep working, as they use the
367379 identifier.
368380
369Import from Emacs reads =denote-directory=, =denote-journal-directory=,
370=denote-journal-keyword= and =denote-journal-title-format=. Denote notes in Markdown or
371plain text are not supported.
381Import from Emacs reads =denote-directory=, =denote-prompts=, =denote-templates=,
382=denote-journal-directory=, =denote-journal-keyword= and =denote-journal-title-format=.
383Templates that are functions, and Denote notes in Markdown or plain text, are not
384supported.
372385
373386* Inline images
374387
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
179179| =org-track-ordered-property-with-tag= | |
180180| =org-timer-format=, =org-timer-default-timer= | |
181181| =org-roam-directory=, =org-roam-dailies-directory=, =org-roam-dailies-file=, =org-roam-dailies-head=, =org-roam-dailies-entry= | |
182| =notes-package=, =denote-directory=, =denote-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= | |
183183| =org-attach-id-dir=, =org-attach-use-inheritance= | |
184184| =org-yank-image-save-method=, =org-yank-dnd-method= | |
185185| =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
241241| =org-roam-dailies-entry= | string | ="* %?"= | The capture template Capture to Daily Note files. See [[file:09-links.org][Links]]. |
242242| =notes-package= | string | ="org-roam"= | Whose conventions Find Node…, Insert Node Link… and the daily-note commands follow: ="org-roam"= or ="denote"=. |
243243| =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=. |
244245| =denote-journal-directory= | string | ="journal"= | The folder journal entries are in, relative to =denote-directory=. Mirrors =denote-journal-directory=. |
245246| =denote-journal-keyword= | string | ="journal"= | The keyword journal entries have. Mirrors =denote-journal-keyword=. |
246247| =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"
363364
364365Keys 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.
365366
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
366379** [[publish]]
367380
368381Publishing 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=, =
624637| =org-track-ordered-property-with-tag= | A tag name as given; =t= becomes ="t"=, =nil= ="nil"= |
625638| =org-roam-directory=, =org-roam-dailies-directory= | The same keys, when the value is a string or a form that makes one |
626639| =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 |
627642| =denote-journal-title-format= | The same key; the symbols =day-date-month-year=, =-24h= and =-12h= become their formats |
628643| =org-roam-dailies-capture-templates= | =org-roam-dailies-file=, =-head= and =-entry=, from the first template's =(file+head NAME HEAD)= target and template |
629644| =org-timer-format=, =org-timer-default-timer= | The same keys; a number becomes a string |