Commit eda8fce281

eda8fce281cb165bf8e1bdf1dcdb24ae82947fe0

parent: e159ec59df

Verified · cmc

cmc <hello@cleberg.net> · 2026-10-11 11:05 UTC

Configurable refile targets

Ports org-refile-get-targets: org-refile-targets as Lisp (nil, org-agenda-files, files; :maxlevel, :level, :tag, :todo, :regexp, t), org-refile-use-outline-path (all six modes, with the (file) suffix for other files), and org-refile-allow-creating-parent-nodes via org-refile-new-child on Mac and iOS. Empty org-refile-targets keeps the previous default. Imported from Emacs.

Closes #19

Layout: unified · split

Sources/OrgApp/DocumentSession.swift +80
@@ -649,6 +649,86 @@ public final class DocumentSession {
649649 }
650650 }
651651
652 /// `org-refile-new-child`: a heading `title` at the end of `parent`'s subtree, one level
653 /// below it, or at the end of the file for a file target. Returns the new heading as a
654 /// target, or a message.
655 public func createRefileChild(under parent: RefileTarget, title: String, now: Date = Date()) -> Result<RefileTarget, RefileFailure> {
656 let name = (parent.path as NSString).lastPathComponent
657 func insert(into state: DocumentState) -> (edit: TextEdit, start: Int, level: Int)? {
658 guard let start = parent.locate(in: state) else { return nil }
659 return Self.newChild(state.text, under: start, title: title)
660 }
661 func target(_ start: Int, _ level: Int, _ hash: String) -> RefileTarget {
662 RefileTarget(label: parent.label + "/" + title, path: parent.path, start: start, title: title, level: level, contentHash: hash)
663 }
664 if let open = entry(parent.path) {
665 let state = open.buffer.document
666 guard state.isEditable else { return .failure(.message("\(name) isn't UTF-8, so it can't be changed.")) }
667 guard let (edit, start, level) = insert(into: state) else { return .failure(.message("Can't find \(parent.label) any more.")) }
668 if case .failed(let message) = open.buffer.perform(PrecomputedEdit(EditResult(baseRevision: state.revision, edits: [edit])), now: now, answers: [:]) {
669 return .failure(.message(message))
670 }
671 changed(open)
672 return .success(target(start, level, ""))
673 }
674 do {
675 let url = URL(fileURLWithPath: parent.path)
676 guard let bytes = try fileSystem.read(url) else { return .failure(.message("\(name) no longer exists.")) }
677 var state = loaded(bytes, path: url.path)
678 guard state.isEditable else { return .failure(.message("\(name) isn't UTF-8, so it can't be changed.")) }
679 guard let (edit, start, level) = insert(into: state) else { return .failure(.message("Can't find \(parent.label) any more.")) }
680 try state.apply([edit], baseRevision: state.revision)
681 if case .conflict = try saver.save(&state, to: url) { return .failure(.message("\(name) changed on disk; nothing was added.")) }
682 return .success(target(start, level, FileRecord.hash(state.mergeBase)))
683 } catch {
684 return .failure(.message("Can't add \(title): \(error.localizedDescription)"))
685 }
686 }
687
688 public enum RefileFailure: Error, Equatable {
689 case message(String)
690 }
691
692 /// The edit `org-refile-new-child` makes in `text` under the heading at `start` (nil for
693 /// the file), and where the new heading starts and its level.
694 static func newChild(_ text: String, under start: Int??, title: String) -> (edit: TextEdit, start: Int, level: Int) {
695 let ns = text as NSString
696 var prefix = ""
697 var pos = ns.length
698 var level = 1
699 if case .some(.some(let heading)) = start {
700 var stars = 0
701 while heading + stars < ns.length, ns.character(at: heading + stars) == 42 { stars += 1 }
702 level = stars + 1
703 // `org-end-of-subtree t t`: the next heading at this level or above.
704 var at = NSMaxRange(ns.lineRange(for: NSRange(location: heading, length: 0)))
705 pos = ns.length
706 while at < ns.length {
707 let line = ns.lineRange(for: NSRange(location: at, length: 0))
708 var n = 0
709 while at + n < NSMaxRange(line), ns.character(at: at + n) == 42 { n += 1 }
710 if n > 0, n <= stars, at + n < ns.length, [32, 9].contains(ns.character(at: at + n)) {
711 pos = at
712 break
713 }
714 at = NSMaxRange(line)
715 }
716 } else if ns.length > 0, ns.character(at: ns.length - 1) != 10 {
717 prefix = "\n"
718 }
719 // `org-back-over-empty-lines`.
720 var back = pos
721 while back > 0, [32, 9, 10, 13].contains(ns.character(at: back - 1)) { back -= 1 }
722 var lineAfter = back
723 while lineAfter < ns.length, ns.character(at: lineAfter) != 10 { lineAfter += 1 }
724 if lineAfter < ns.length { lineAfter += 1 }
725 if !prefix.isEmpty { lineAfter = ns.length }
726 let at = min(lineAfter, pos)
727 let insertion = prefix + "\n" + String(repeating: "*", count: level) + " " + title + "\n"
728 let newStart = at + (prefix as NSString).length + 1
729 return (TextEdit(range: at..<at, replacement: insertion), newStart, level)
730 }
731
652732 /// Archives the subtree at the caret, or at `from`, where `org-archive-subtree` would.
653733 /// Returns a message.
654734 @discardableResult
Sources/OrgApp/EmacsImport.swift +12
@@ -532,6 +532,18 @@ public struct EmacsImport: Sendable {
532532 } else {
533533 add(name, .bool(truthy))
534534 }
535 case "org-refile-targets":
536 switch RefileSettings.parseTargets(value.description) {
537 case .success: add(name, .string(value.description))
538 case .failure(.message(let message)): note(message)
539 }
540 case "org-refile-use-outline-path":
541 let mode = value.symbol ?? "nil"
542 guard RefileSettings.OutlinePath(rawValue: mode) != nil else { return note("unexpected value \(value.description)") }
543 add(name, .string(mode))
544 case "org-refile-allow-creating-parent-nodes":
545 let mode = value.symbol ?? "nil"
546 add(name, .string(RefileSettings.Creating(rawValue: mode) == nil ? "t" : mode))
535547 case "org-stuck-projects":
536548 // `("+LEVEL=2/-DONE" ("TODO" "NEXT") nil "")`.
537549 guard let parts = value.elements, parts.count == 4, let match = parts[0].string else { return note("not a stuck-projects definition") }
Sources/OrgApp/OrgPreferences.swift +7
@@ -120,6 +120,13 @@ public enum OrgPreferences {
120120 public static func agendaFiles(_ defaults: UserDefaults = .standard) -> [String] {
121121 string("agendaFiles", defaults).components(separatedBy: .newlines).map { $0.trimmingCharacters(in: .whitespaces) }.filter { !$0.isEmpty }
122122 }
123 /// `org-refile-targets`, `org-refile-use-outline-path` and
124 /// `org-refile-allow-creating-parent-nodes`; targets that can't be read are orgstar's default.
125 public static func refileSettings(_ defaults: UserDefaults = .standard) -> RefileSettings {
126 let targets = (try? RefileSettings.parseTargets(string("refileTargets", defaults)).get()) ?? RefileSettings.workspaceTargets
127 return RefileSettings(targets: targets, outlinePath: RefileSettings.OutlinePath(rawValue: string("refileUseOutlinePath", defaults)) ?? .file,
128 creating: RefileSettings.Creating(rawValue: string("refileAllowCreatingParentNodes", defaults)) ?? .no)
129 }
123130 /// `org-stuck-projects`.
124131 public static func stuckProjects(_ defaults: UserDefaults = .standard) -> StuckProjects {
125132 StuckProjects(match: string("stuckProjectsMatch", defaults), todo: words(string("stuckProjectsTodo", defaults)),
Sources/OrgApp/RefileTargets.swift added +285
@@ -0,0 +1,285 @@
1import Foundation
2import OrgCore
3import OrgDocument
4import OrgIndex
5import OrgPresentation
6
7/// `org-refile-targets`, `org-refile-use-outline-path` and
8/// `org-refile-allow-creating-parent-nodes` (Org 9.8.7).
9public struct RefileSettings: Sendable, Equatable {
10 /// Where an `org-refile-targets` entry looks.
11 public enum Files: Sendable, Equatable {
12 /// `nil`: the file refiled from.
13 case current
14 case agendaFiles
15 case paths([String])
16 /// Every org file in the folders: orgstar's default.
17 case workspace
18 }
19
20 /// Which headings an entry offers.
21 public enum Spec: Sendable, Equatable {
22 /// `t`: every heading.
23 case all
24 case tag(String), todo(String)
25 /// An Emacs regexp.
26 case regexp(String)
27 case level(Int), maxLevel(Int)
28 }
29
30 public struct Target: Sendable, Equatable {
31 public var files: Files
32 public var spec: Spec
33
34 public init(files: Files, spec: Spec) {
35 self.files = files
36 self.spec = spec
37 }
38 }
39
40 public enum OutlinePath: String, Sendable, CaseIterable {
41 case none = "nil", full = "t", file, fullFilePath = "full-file-path", bufferName = "buffer-name", title
42 }
43
44 public enum Creating: String, Sendable, CaseIterable {
45 case no = "nil", yes = "t", confirm
46 }
47
48 public enum Failure: Error, Equatable {
49 case message(String)
50 }
51
52 public var targets: [Target]
53 public var outlinePath: OutlinePath
54 public var creating: Creating
55
56 /// Headings down to level 3 in every file, as orgstar offers with no `org-refile-targets`.
57 public static let workspaceTargets = [Target(files: .workspace, spec: .maxLevel(3))]
58
59 public init(targets: [Target] = workspaceTargets, outlinePath: OutlinePath = .file, creating: Creating = .no) {
60 self.targets = targets
61 self.outlinePath = outlinePath
62 self.creating = creating
63 }
64
65 /// An `org-refile-targets` value as Lisp writes it: `((nil :maxlevel . 3)
66 /// (org-agenda-files :tag . "project") ("~/notes/x.org" :level . 1))`. Empty text is
67 /// orgstar's default.
68 public static func parseTargets(_ text: String) -> Result<[Target], Failure> {
69 guard text.contains(where: { !$0.isWhitespace }) else { return .success(workspaceTargets) }
70 let value: Sexp
71 do {
72 guard let form = try LispReader.read(text).first?.sexp else { return .success(workspaceTargets) }
73 value = form
74 } catch {
75 return .failure(.message("can't read \(text)"))
76 }
77 func unquote(_ s: Sexp) -> Sexp {
78 if case .list(let items) = s, items.count == 2, items[0].symbol == "quote" { return items[1] }
79 return s
80 }
81 guard let entries = unquote(value).elements else { return .failure(.message("not a list of targets")) }
82 var targets: [Target] = []
83 for entry in entries {
84 // `(FILES . (KEY . VALUE))`, read as `(FILES KEY . VALUE)`, or `(FILES KEY VALUE)`.
85 let head: Sexp
86 var key: String?
87 var argument: Sexp?
88 switch entry {
89 case .dotted(let items, let last) where items.count == 2:
90 head = items[0]
91 key = items[1].symbol
92 argument = last
93 case .list(let items) where items.count == 3:
94 head = items[0]
95 key = items[1].symbol
96 argument = items[2]
97 case .dotted(let items, let last) where items.count == 1 && last.symbol == "t":
98 head = items[0]
99 key = "t"
100 default:
101 return .failure(.message("\(entry.description) isn't a target"))
102 }
103 let files: Files
104 switch head {
105 case .symbol("nil"): files = .current
106 case .symbol("org-agenda-files"): files = .agendaFiles
107 case .string(let path): files = .paths([path])
108 case .list(let items) where items.allSatisfy({ $0.string != nil }): files = .paths(items.compactMap(\.string))
109 default: return .failure(.message("files \(head.description) aren't supported"))
110 }
111 let spec: Spec
112 switch (key, argument) {
113 case ("t"?, _): spec = .all
114 case (":tag"?, .string(let s)?): spec = .tag(s)
115 case (":todo"?, .string(let s)?): spec = .todo(s)
116 case (":regexp"?, .string(let s)?): spec = .regexp(s)
117 case (":level"?, .integer(let n)?): spec = .level(n)
118 case (":maxlevel"?, .integer(let n)?): spec = .maxLevel(n)
119 default: return .failure(.message("\(entry.description) isn't a target"))
120 }
121 targets.append(Target(files: files, spec: spec))
122 }
123 return .success(targets)
124 }
125
126 /// For an answer that isn't a target, `parent/child` with `parent` one: the target and the
127 /// new heading's title, as `org-refile-get-location` splits it.
128 public static func newNode(_ answer: String, in targets: [RefileTarget]) -> (parent: RefileTarget, child: String)? {
129 guard let m = answer.firstMatch(of: /^(.*)\/([^\/]+)$/) else { return nil }
130 let parent = String(m.1).replacingOccurrences(of: "/$", with: "", options: .regularExpression)
131 let child = String(m.2).trimmingCharacters(in: .whitespaces)
132 guard !child.isEmpty, let target = targets.first(where: { $0.label == parent }) else { return nil }
133 return (target, child)
134 }
135
136 /// `org-refile-get-targets`'s `descre` for `spec`, in Emacs syntax.
137 static func regexp(_ spec: Spec) -> String {
138 func quote(_ s: String) -> String { s.map { "[*.\\?+^$".contains($0) ? "\\" + String($0) : String($0) }.joined() }
139 switch spec {
140 case .all: return "^\\*+[ \t]"
141 case .tag(let tag): return "^\\*+[ \t]+.*?:" + quote(tag) + ":"
142 case .todo(let keyword): return "^\\*+[ \t]+" + quote(keyword) + "[ \t]"
143 case .regexp(let re): return re
144 case .level(let n): return "^\\*\\{\(n)\\}[ \t]"
145 case .maxLevel(let n): return "^\\*\\{1,\(n)\\}[ \t]"
146 }
147 }
148}
149
150extension WorkspaceModel {
151 /// The refile targets, as `org-refile-get-targets` lists them for `settings`: entry by
152 /// entry, file by file, in buffer order, with a file's own target first when the outline
153 /// path starts with the file. `openPath` is the file refiled from, read from `document`.
154 public func refileTargets(openPath: String?, document: DocumentState?, settings: RefileSettings = OrgPreferences.refileSettings()) -> [RefileTarget] {
155 var targets: [RefileTarget] = []
156 var seen: Set<String> = []
157 func add(_ target: RefileTarget) {
158 if seen.insert("\(target.path)\u{0}\(target.start ?? -1)\u{0}\(target.label)").inserted { targets.append(target) }
159 }
160 let orgFiles = files.filter { $0.kind == .org }
161 let relative = Dictionary(orgFiles.map { ($0.path, $0.relativePath) }, uniquingKeysWith: { a, _ in a })
162 // Closed files' headings, from the index, for the targets that go by level.
163 let levels = settings.targets.compactMap { target -> Int? in
164 switch target.spec {
165 case .all: Int.max
166 case .level(let n), .maxLevel(let n): n
167 default: nil
168 }
169 }
170 let indexed = levels.isEmpty ? [] : (try? index.outline(maxLevel: min(levels.max()!, 1000))) ?? []
171 let indexedByPath = Dictionary(grouping: indexed, by: \.location.path)
172 for entry in settings.targets {
173 let paths: [String]
174 switch entry.files {
175 case .current: paths = openPath.map { [$0] } ?? []
176 case .workspace: paths = orgFiles.map(\.path)
177 case .agendaFiles:
178 let list = OrgPreferences.agendaFiles()
179 if list.isEmpty {
180 let subfolders = OrgPreferences.agendaSubfolders()
181 paths = orgFiles.filter { !$0.name.hasPrefix(".") && (subfolders || !$0.relativePath.contains("/")) }.map(\.path).sorted()
182 } else {
183 paths = AgendaFiles.resolve(list, base: rootPaths.first)
184 }
185 case .paths(let list):
186 let base = openPath.map { ($0 as NSString).deletingLastPathComponent } ?? rootPaths.first
187 paths = list.map { entry in
188 let path = (entry as NSString).expandingTildeInPath
189 return ((path.hasPrefix("/") || base == nil ? path : (base! as NSString).appendingPathComponent(path)) as NSString).standardizingPath
190 }
191 }
192 for path in paths {
193 let name = relative[path] ?? (path as NSString).lastPathComponent
194 // The headings: from the buffer, the index, or the file's text.
195 var text: String?
196 var hash: String
197 var headings: [(start: Int, level: Int, path: [String])] = []
198 if path == openPath, let document {
199 text = document.text
200 hash = FileRecord.hash(document.mergeBase)
201 } else if let level = Self.level(entry.spec), let records = indexedByPath[path] {
202 hash = records.first?.location.contentHash ?? ""
203 headings = records.filter { level($0.level) }.map { ($0.location.start, $0.level, $0.outlinePath) }
204 } else {
205 guard let data = FileManager.default.contents(atPath: path) else { continue }
206 let state = DocumentState(bytes: [UInt8](data))
207 text = state.text
208 hash = FileRecord.hash(state.mergeBase)
209 }
210 if let text {
211 headings = Self.headings(text, spec: entry.spec)
212 }
213 let base: String? = switch settings.outlinePath {
214 case .file, .bufferName: name
215 case .fullFilePath: path
216 case .title: text.flatMap { Self.fileTitle($0) } ?? Self.diskTitle(path) ?? name
217 case .none, .full: nil
218 }
219 // Targets in other files name the file after them, but not with paths that start with it.
220 let elsewhere = path != openPath && [.none, .full, .bufferName].contains(settings.outlinePath)
221 let suffix = elsewhere ? " (\((path as NSString).lastPathComponent))" : ""
222 if let base, settings.outlinePath != .none, settings.outlinePath != .full {
223 add(RefileTarget(label: base + suffix, path: path, start: nil, title: "", level: 0, contentHash: hash))
224 }
225 for heading in headings {
226 let escaped = heading.path.map { $0.replacingOccurrences(of: "/", with: "\\/") }
227 var label = settings.outlinePath == .none ? heading.path.last ?? "" : ((base.map { [$0] } ?? []) + escaped).joined(separator: "/")
228 label += suffix
229 add(RefileTarget(label: label, path: path, start: heading.start, title: heading.path.last ?? "", level: heading.level, contentHash: hash))
230 }
231 }
232 }
233 return targets
234 }
235
236 /// The test a level-based spec makes of a heading's level; nil for the others.
237 static func level(_ spec: RefileSettings.Spec) -> ((Int) -> Bool)? {
238 switch spec {
239 case .all: { _ in true }
240 case .level(let n): { $0 == n }
241 case .maxLevel(let n): { $0 <= n }
242 default: nil
243 }
244 }
245
246 /// The headings `spec` finds in `text`, as `org-refile-get-targets` searches: each match
247 /// of its regexp (case-sensitive) on a heading line gives that heading.
248 static func headings(_ text: String, spec: RefileSettings.Spec) -> [(start: Int, level: Int, path: [String])] {
249 let outline = Presentation.outline(OrgParser.parse(text))
250 var paths: [[String]] = []
251 for entry in outline { paths.append((entry.parent.map { paths[$0] } ?? []) + [entry.title]) }
252 let byStart = Dictionary(outline.indices.map { (outline[$0].start, $0) }, uniquingKeysWith: { a, _ in a })
253 guard let regex = try? NSRegularExpression(pattern: EmacsRegex.translate(RefileSettings.regexp(spec)), options: .anchorsMatchLines) else { return [] }
254 let ns = text as NSString
255 var found: [(Int, Int, [String])] = []
256 var at = 0
257 while at <= ns.length, let m = regex.firstMatch(in: text, options: [.withoutAnchoringBounds, .withTransparentBounds], range: NSRange(location: at, length: ns.length - at)) {
258 let end = NSMaxRange(m.range)
259 let line = ns.lineRange(for: NSRange(location: min(end, max(0, ns.length - 1)), length: 0))
260 let lineStart = end == ns.length && end > 0 && ns.character(at: end - 1) == 10 ? end : line.location
261 if let index = byStart[lineStart] {
262 found.append((lineStart, outline[index].level, paths[index]))
263 var lineEnd = NSMaxRange(line)
264 if lineEnd > line.location, ns.character(at: lineEnd - 1) == 10 { lineEnd -= 1 }
265 at = max(lineEnd, end, at + 1)
266 } else {
267 at = max(end, at + 1)
268 }
269 }
270 return found
271 }
272
273 /// `org-get-title`: the `#+TITLE` lines joined.
274 static func fileTitle(_ text: String) -> String? {
275 let titles = text.components(separatedBy: "\n").compactMap { line -> String? in
276 guard let r = line.range(of: "^#\\+(?i:title):[ \\t]*", options: .regularExpression) else { return nil }
277 return String(line[r.upperBound...]).trimmingCharacters(in: .whitespaces)
278 }
279 return titles.isEmpty ? nil : titles.joined(separator: " ")
280 }
281
282 static func diskTitle(_ path: String) -> String? {
283 FileManager.default.contents(atPath: path).flatMap { String(data: $0, encoding: .utf8) }.flatMap { fileTitle($0) }
284 }
285}
Sources/OrgApp/UserConfig.swift +6
@@ -203,6 +203,12 @@ public enum UserConfig {
203203 comment: "t: marking the clocked entry done clocks out; nil: it doesn't; or keywords that clock out, separated by spaces", legacy: ""),
204204 Setting(section: "", key: "org-clock-history-length", defaultsKey: "clockHistoryLength", kind: .integer, fallback: .integer(5),
205205 comment: "recently clocked entries to remember", legacy: ""),
206 Setting(section: "", key: "org-refile-targets", defaultsKey: "refileTargets", kind: .string, fallback: .string(""),
207 comment: "as Lisp: ((nil :maxlevel . 3) (org-agenda-files :tag . \"project\")); \"\" offers headings to level 3 in every file", legacy: ""),
208 Setting(section: "", key: "org-refile-use-outline-path", defaultsKey: "refileUseOutlinePath", kind: .string, fallback: .string("file"),
209 comment: "how targets are named: nil, t, file, full-file-path, buffer-name or title", legacy: ""),
210 Setting(section: "", key: "org-refile-allow-creating-parent-nodes", defaultsKey: "refileAllowCreatingParentNodes", kind: .string, fallback: .string("nil"),
211 comment: "a target typed as parent/new adds the heading: t, confirm (asks first) or nil", legacy: ""),
206212 Setting(section: "", key: "org-agenda-files", defaultsKey: "agendaFiles", kind: .string, fallback: .string(""),
207213 comment: "files and folders the agenda reads, separated by \\n; a file that isn't .org lists more, one per line; \"\" reads the folders' files", legacy: ""),
208214 Setting(section: "", key: "org-agenda-use-time-grid", defaultsKey: "agendaUseTimeGrid", kind: .bool, fallback: .bool(true),
Sources/OrgApp/WorkspaceModel.swift −30
@@ -395,36 +395,6 @@ public final class WorkspaceModel {
395395 return [path: record]
396396 }
397397
398 /// Headings down to level 3 in every org file, and each file itself. The open file's come
399 /// from its buffer, so they match unsaved edits.
400 public func refileTargets(openPath: String?, document: DocumentState?) -> [RefileTarget] {
401 let indexed = (try? index.outline(maxLevel: 3)) ?? []
402 var targets: [RefileTarget] = []
403 for file in files where file.kind == .org {
404 let name = file.relativePath
405 if file.path == openPath, let document {
406 let hash = FileRecord.hash(document.mergeBase)
407 targets.append(RefileTarget(label: name, path: file.path, start: nil, title: "", level: 0, contentHash: hash))
408 var stack: [String] = []
409 for entry in Presentation.outline(document.tree) {
410 stack = Array(stack.prefix(entry.level - 1)) + [entry.title]
411 guard entry.level <= 3 else { continue }
412 targets.append(RefileTarget(label: name + "/" + stack.joined(separator: "/"), path: file.path, start: entry.start, title: entry.title, level: entry.level, contentHash: hash))
413 }
414 continue
415 }
416 let headings = indexed.filter { $0.location.path == file.path }
417 targets.append(RefileTarget(label: name, path: file.path, start: nil, title: "", level: 0, contentHash: headings.first?.location.contentHash ?? ""))
418 for heading in headings {
419 targets.append(RefileTarget(
420 label: name + "/" + heading.outlinePath.joined(separator: "/"), path: file.path, start: heading.location.start,
421 title: heading.location.title, level: heading.level, contentHash: heading.location.contentHash
422 ))
423 }
424 }
425 return targets
426 }
427
428398 public func quickOpen(_ query: String) -> [FileEntry] {
429399 FuzzyMatch.rank(query, files.filter { $0.kind != .conflict })
430400 }
Sources/OrgCore/Agenda/AgendaSearch.swift +2 −2
@@ -552,7 +552,7 @@ public struct TagsMatcher: Sendable {
552552
553553/// Emacs regular expressions run through ICU, case-insensitively as the matcher binds
554554/// `case-fold-search`.
555enum EmacsRegex {
555public enum EmacsRegex {
556556 /// Characters without word syntax in an Org buffer under Emacs 31, as ranges: everything
557557 /// else, `$`, `%` and `'` included, is a word character. Emacs also puts a word boundary
558558 /// where the script changes, which this doesn't.
@@ -576,7 +576,7 @@ enum EmacsRegex {
576576 + "\\x{fe59}-\\x{fe5e}\\x{ff01}-\\x{ff0f}\\x{ff1b}-\\x{ff20}\\x{ff3b}-\\x{ff40}\\x{ff5b}-\\x{ff65}"
577577 + "\\x{ffe0}-\\x{ffe3}\\x{ffe5}\\x{11660}-\\x{1166c}\\x{1fb00}-\\x{1fbff}"
578578 /// `search` uses `org-search-view`'s syntax table, where `'` is punctuation.
579 static func translate(_ pattern: String, search: Bool = false) -> String {
579 public static func translate(_ pattern: String, search: Bool = false) -> String {
580580 let nonWord = search ? Self.nonWord + "'" : Self.nonWord
581581 let word = "[^" + nonWord + "]"
582582 var out = ""
Sources/Orgstar/ContentView.swift +18 −2
@@ -786,8 +786,24 @@ struct ContentView: View {
786786 let keep = id == "app.refile.copy"
787787 let targets = workspace.refileTargets(openPath: session.path, document: session.document)
788788 commands.ask(Prompt(key: "refile", message: keep ? "Copy to:" : "Refile to:", choices: targets.map(\.label))) { answer in
789 guard let answer, let target = targets.first(where: { $0.label == answer }) else { return }
790 if let message = session.refile(to: target, keep: keep) { commands.show(message) }
789 guard let answer else { return }
790 if let target = targets.first(where: { $0.label == answer }) {
791 if let message = session.refile(to: target, keep: keep) { commands.show(message) }
792 return
793 }
794 // `org-refile-allow-creating-parent-nodes`: `parent/new` adds the heading first.
795 let creating = OrgPreferences.refileSettings().creating
796 guard creating != .no, let (parent, child) = RefileSettings.newNode(answer, in: targets) else { return commands.show("Invalid target location") }
797 let create = {
798 switch session.createRefileChild(under: parent, title: child) {
799 case .success(let target): if let message = session.refile(to: target, keep: keep) { commands.show(message) }
800 case .failure(.message(let message)): commands.show(message)
801 }
802 }
803 guard creating == .confirm else { return create() }
804 commands.ask(Prompt(key: "confirm", message: "Create new node \"\(child)\"?", choices: ["yes", "no"])) { reply in
805 if reply == "yes" { create() }
806 }
791807 }
792808 case "app.refile.goto":
793809 // `C-u C-c C-w`: the target heading, or the end of a file.
Sources/OrgstarMobile/AgendaScreen.swift +10
@@ -960,6 +960,9 @@ struct FilterSheet: View {
960960/// as the Mac's prompt offers them, searchable by their path.
961961struct RefileSheet: View {
962962 let targets: [RefileTarget]
963 /// `org-refile-allow-creating-parent-nodes`: `parent/new` in the search field offers to
964 /// add the heading.
965 var create: ((RefileTarget, String) -> Void)?
963966 let choose: (RefileTarget?) -> Void
964967 @State private var query = ""
965968
@@ -977,6 +980,13 @@ struct RefileSheet: View {
977980 var body: some View {
978981 NavigationStack {
979982 List {
983 if let create, let (parent, child) = RefileSettings.newNode(query, in: targets) {
984 Button {
985 create(parent, child)
986 } label: {
987 Label("New heading “\(child)” under \(parent.label)", systemImage: "plus")
988 }
989 }
980990 ForEach(files, id: \.path) { file in
981991 Section {
982992 ForEach(file.targets, id: \.self) { target in
Sources/OrgstarMobile/EditorScreen.swift +10 −1
@@ -109,7 +109,16 @@ struct EditorScreen: View {
109109 case .syncCopies: SyncConflictSheet(session: session) { message = $0 }
110110 case .recovery: RecoverySheet(session: session) { message = $0 }
111111 case .refile(let command):
112 RefileSheet(targets: workspace.refileTargets(openPath: session.path, document: session.document)) { target in
112 RefileSheet(targets: workspace.refileTargets(openPath: session.path, document: session.document),
113 create: command == "app.refile.goto" || OrgPreferences.refileSettings().creating == .no ? nil : { parent, child in
114 self.sheet = nil
115 switch session.createRefileChild(under: parent, title: child) {
116 case .success(let target):
117 guard let path = session.path, let editor else { return }
118 message = session.refile(to: target, from: (path, editor.editContext().caret), keep: command == "app.refile.copy")
119 case .failure(.message(let text)): message = text
120 }
121 }) { target in
113122 self.sheet = nil
114123 guard let target else { return }
115124 if command == "app.refile.goto" {
Tests/OrgAppTests/EmacsImportTests.swift +7 −1
@@ -32,6 +32,9 @@ struct EmacsImportTests {
3232 ("x" "Prefix")
3333 ("f" "Function" my-agenda-function)))
3434 (add-to-list 'org-agenda-custom-commands '("s" "Stuck" stuck ""))
35 (setq org-refile-targets '((nil :maxlevel . 2) (org-agenda-files :tag . "project"))
36 org-refile-use-outline-path 'title
37 org-refile-allow-creating-parent-nodes 'confirm)
3538 (setq fill-column (+ 70 2))
3639 (add-to-list 'org-structure-template-alist '("el" . "src emacs-lisp"))
3740 (with-eval-after-load 'org (add-to-list 'org-structure-template-alist '("q" . "QUOTE")))
@@ -111,6 +114,9 @@ struct EmacsImportTests {
111114 #expect(s["org-agenda-time-grid.times"] == .string("800 1300"))
112115 #expect(s["org-agenda-use-time-grid"] == .bool(false))
113116 #expect(s["org-agenda-files"] == .string("~/notes/\n~/work/plan.org"))
117 #expect(s["org-refile-targets"] == .string("((nil :maxlevel . 2) (org-agenda-files :tag . \"project\"))"))
118 #expect(s["org-refile-use-outline-path"] == .string("title"))
119 #expect(s["org-refile-allow-creating-parent-nodes"] == .string("confirm"))
114120 #expect(s["org-stuck-projects.match"] == .string("+project/-DONE"))
115121 #expect(s["org-stuck-projects.todo"] == .string("NEXT TODO"))
116122 #expect(s["org-stuck-projects.tags"] == .string("errand"))
@@ -218,7 +224,7 @@ struct EmacsImportTests {
218224 let keymap = folder.appendingPathComponent("keymap.toml")
219225 #expect(KeymapLoader.load(.doom, userFile: keymap).problems.isEmpty)
220226 #expect(KeymapLoader.load(.doom, userFile: keymap).keymap.keyLabels(for: "app.agenda", modes: ["normal"]).contains("C-c a"))
221 #expect(summary.hasPrefix("Imported 43 settings, 3 capture templates, 3 key bindings, 2 structure templates, 3 agenda views."), "\(summary)")
227 #expect(summary.hasPrefix("Imported 46 settings, 3 capture templates, 3 key bindings, 2 structure templates, 3 agenda views."), "\(summary)")
222228 let views = AgendaViewLoader.load(userFile: folder.appendingPathComponent("views.toml"))
223229 #expect(views.problems.isEmpty, "\(views.problems)")
224230 #expect(views.views.dropFirst(3).map(\.name) == ["Daily", "Work", "Stuck"])
Tests/OrgAppTests/RefileTargetTests.swift added +106
@@ -0,0 +1,106 @@
1import Foundation
2import Testing
3@testable import OrgApp
4import OrgCore
5import OrgDocument
6
7/// `org-refile-get-targets` against Emacs.
8@MainActor
9struct RefileTargetTests {
10 static let files = [
11 ("a.org", "* Projects :proj:\n** TODO Website\n*** Plan the copy\n** Taxes/2026\n* NEXT Write report\n* Notes\n"),
12 ("b.org", "* Inbox\n** Plan ahead :proj:\n* Someday\n** NEXT Read\n"),
13 ("sub/x.org", "#+TITLE: Extra file\n* Deep\n** Deeper\n"),
14 ]
15
16 static var emacs: String { ProcessInfo.processInfo.environment["ORGSTAR_EMACS"] ?? "emacs" }
17
18 /// Emacs's labels as `org-refile-get-location` shows them, without the `/` it adds for
19 /// completion, with the file and the heading's start (0-based) of each.
20 static func emacsTargets(_ folder: URL, targets: String, mode: String) throws -> [String] {
21 let form = """
22 (progn
23 (require 'org) (require 'org-refile) (require 'json)
24 (let* ((dir "\(folder.path)/")
25 (a (expand-file-name "a.org" dir)))
26 (setq org-agenda-files (list a (expand-file-name "b.org" dir)))
27 (with-current-buffer (find-file-noselect a)
28 (let* ((org-refile-targets '\(targets))
29 (org-refile-use-outline-path '\(mode))
30 (extra (if org-refile-use-outline-path "/" ""))
31 (out nil))
32 (dolist (x (org-refile-get-targets))
33 (let ((label (if (and (not (memq org-refile-use-outline-path '(file full-file-path title)))
34 (not (equal (file-truename a) (file-truename (nth 1 x)))))
35 (concat (car x) " (" (file-name-nondirectory (nth 1 x)) ")")
36 (car x))))
37 (push (format "%s | %s | %s" label (file-name-nondirectory (nth 1 x))
38 (let ((p (nth 3 x))) (if p (1- (if (markerp p) (marker-position p) p)) "-")))
39 out)))
40 (princ (json-encode (nreverse out)))))))
41 """
42 let process = Process()
43 process.executableURL = URL(fileURLWithPath: "/usr/bin/env")
44 process.arguments = [emacs, "-Q", "--batch", "--eval", form]
45 let pipe = Pipe()
46 process.standardOutput = pipe
47 let errors = Pipe()
48 process.standardError = errors
49 try process.run()
50 let data = pipe.fileHandleForReading.readDataToEndOfFile()
51 process.waitUntilExit()
52 guard let decoded = try? JSONDecoder().decode([String].self, from: data) else {
53 Issue.record("Emacs printed \(String(decoding: errors.fileHandleForReading.readDataToEndOfFile(), as: UTF8.self))")
54 return []
55 }
56 return decoded
57 }
58
59 @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
60 func targetsLikeOrg() async throws {
61 let notes = try Folder()
62 for (name, text) in Self.files { try notes.write(name, text) }
63 let workspace = try WorkspaceModel(directory: nil)
64 try await workspace.addRoot(notes.url)
65 let a = notes.url.appendingPathComponent("a.org").standardizedFileURL.path
66 let document = DocumentState(bytes: Array(Self.files[0].1.utf8))
67 let cases: [(String, String)] = [
68 ("((nil :maxlevel . 2))", "file"),
69 ("((org-agenda-files :level . 2))", "t"),
70 ("((nil :tag . \"proj\") (org-agenda-files :todo . \"NEXT\"))", "nil"),
71 ("((org-agenda-files :regexp . \"Plan\"))", "buffer-name"),
72 ("((\"sub/x.org\" :maxlevel . 9) (nil . t))", "title"),
73 ("((org-agenda-files :maxlevel . 1))", "file"),
74 ]
75 for (targets, mode) in cases {
76 let parsed = try RefileSettings.parseTargets(targets).get()
77 let settings = RefileSettings(targets: parsed, outlinePath: RefileSettings.OutlinePath(rawValue: mode)!)
78 let ours = workspace.refileTargets(openPath: a, document: document, settings: settings).map {
79 "\($0.label) | \(($0.path as NSString).lastPathComponent) | \($0.start.map(String.init) ?? "-")"
80 }
81 let theirs = try Self.emacsTargets(notes.url, targets: targets, mode: mode).map {
82 $0.replacingOccurrences(of: "/ (", with: " (").replacingOccurrences(of: "/ | ", with: " | ")
83 }
84 #expect(ours == theirs, "\(targets) \(mode)")
85 }
86 }
87
88 @Test func newChildGoesAtTheSubtreesEnd() {
89 func run(_ text: String, _ start: Int?, _ title: String) -> (String, Int, Int) {
90 let r = DocumentSession.newChild(text, under: .some(start), title: title)
91 return (r.edit.apply(to: text), r.start, r.level)
92 }
93 #expect(run("* A\nbody\n\n* B\n", 0, "New") == ("* A\nbody\n\n** New\n\n* B\n", 10, 2))
94 #expect(run("* A\n** a1\n* B", 0, "New") == ("* A\n** a1\n\n** New\n* B", 11, 2))
95 #expect(run("* A\nx", nil, "New") == ("* A\nx\n\n* New\n", 7, 1))
96 #expect(run("* A\n\n\n", nil, "New") == ("* A\n\n* New\n\n\n", 5, 1))
97 }
98
99 @Test func splitsNewNodes() {
100 let parent = RefileTarget(label: "a.org/Projects", path: "/a.org", start: 0, title: "Projects", level: 1, contentHash: "")
101 #expect(RefileSettings.newNode("a.org/Projects/Garden", in: [parent])?.child == "Garden")
102 #expect(RefileSettings.newNode("a.org/Projects//Garden", in: [parent])?.child == "Garden")
103 #expect(RefileSettings.newNode("a.org/Other/Garden", in: [parent]) == nil)
104 #expect(RefileSettings.newNode("Garden", in: [parent]) == nil)
105 }
106}
docs/manual/guide/04-outlines.org +33 −8
@@ -747,9 +747,9 @@ normalized.
747747Refile… (=org-refile=, =C-c C-w=, Mac =⌃⌘W=, Doom =SPC m r r= or =SPC m s r=) moves the
748748subtree at the caret under another heading, in this file or another one.
749749
750It asks for the target with completion. The targets are every org file in your folders
751and every heading down to level 3 in those files, written as the file's path relative
752to its folder followed by the outline path:
750It asks for the target with completion. By default the targets are every org file in
751your folders and every heading down to level 3 in those files, written as the file's
752path relative to its folder followed by the outline path:
753753
754754#+BEGIN_EXAMPLE
755755projects.org
@@ -769,10 +769,36 @@ one, otherwise through the normal save path, and removes the subtree from the so
769769only after that succeeds. If the target file changed on disk in the meantime, nothing
770770is refiled.
771771
772This matches Org with =org-refile-targets= set to headings of maximum level 3 in all
773files, =org-refile-use-outline-path= set to =file=, =org-reverse-note-order= =nil= (new
774entries go last), =org-log-refile= =nil= and =org-refile-keep= =nil=. None of these is
775configurable in orgstar. Refiling from the agenda is covered in [[file:07-agenda.org][Agenda]].
772Three settings in =config.toml= change the targets, as in Org (see [[file:13-configuration.org][Configuration]]):
773
774- =org-refile-targets=, written as Lisp: a list of =(FILES . SPEC)=. =FILES= is =nil=
775 (the file you refile from), =org-agenda-files=, a file name, or a list of file names
776 (relative to the current file's folder). =SPEC= is =(:maxlevel . N)=, =(:level . N)=,
777 =(:tag . "TAG")=, =(:todo . "KEYWORD")=, =(:regexp . "RE")= or =t= for every heading;
778 =(nil :maxlevel . 3)= is read the same way. The tag, keyword and regexp tests look at
779 heading lines, case-sensitively.
780
781 #+BEGIN_SRC toml
782 org-refile-targets = "((nil :maxlevel . 3) (org-agenda-files :tag . \"project\"))"
783 #+END_SRC
784
785 Empty (the default) is the list above: every file, to level 3.
786- =org-refile-use-outline-path=: how targets are written. =file= (the default) is the
787 file then the outline path; =t= the outline path alone; =nil= the heading alone;
788 =full-file-path= the file's full path then the outline path; =title= the file's
789 =#+TITLE= (or its name) then the outline path; =buffer-name= as =file=. With =nil=, =t=
790 and =buffer-name=, targets in other files end with the file's name in parentheses,
791 and files are targets only with =file=, =full-file-path=, =title= and =buffer-name=. A
792 =/= in a heading is written =\/=.
793- =org-refile-allow-creating-parent-nodes=: with =t=, typing =TARGET/New heading=, where
794 =TARGET= is one of the targets, adds =New heading= at the end of =TARGET= one level
795 below it (or at the end of the file for a file) and refiles there; =confirm= asks
796 first. On iOS the Refile sheet offers the new heading when the search field holds such
797 a path.
798
799Otherwise this matches Org with =org-reverse-note-order= =nil= (new entries go last),
800=org-log-refile= =nil= and =org-refile-keep= =nil=. Refiling from the agenda is covered
801in [[file:07-agenda.org][Agenda]].
776802
777803Copy to Refile Target… (=org-copy=, =C-c M-w=) asks the same way and copies the
778804subtree there, leaving it in place. Go to Refile Target… (=C-u C-c C-w=, Doom
@@ -898,4 +924,3 @@ These Org structure features are not in orgstar:
898924- Editing values in column view, and writing summaries from it; the
899925 =columnview= dynamic block does write summaries.
900926- The =ORDERED= property, radio lists and timer list items in the list commands.
901- Custom =org-refile-targets=.
docs/manual/guide/13-configuration.org +6
@@ -173,6 +173,7 @@ These settings have no control in the Settings window. Some are in the View menu
173173| =[org-agenda-time-grid]=, =org-agenda-use-time-grid=, =org-agenda-show-current-time-in-grid= | |
174174| =[org-stuck-projects]= | |
175175| =org-agenda-files= | |
176| =org-refile-targets=, =org-refile-use-outline-path=, =org-refile-allow-creating-parent-nodes= | |
176177| =theme-file= | |
177178
178179* config.toml reference
@@ -230,6 +231,9 @@ A key you remove from the file goes back to its default. A key that isn't in the
230231| =org-agenda-tags-todo-honor-ignore-options= | boolean | =false= | The four settings above apply to TODO-only matches (=M=) too. Mirrors =org-agenda-tags-todo-honor-ignore-options=. |
231232| =org-agenda-search-view-always-boolean= | boolean | =false= | The agenda's text search reads every string as =+word -word {regexp}= snippets, never as a phrase. Mirrors =org-agenda-search-view-always-boolean=. |
232233| =org-agenda-search-view-force-full-words= | boolean | =false= | Text search snippets match whole words only, as a leading =:= does. Mirrors =org-agenda-search-view-force-full-words=. |
234| =org-refile-targets= | string | =""= | Refile targets as Lisp, as =org-refile-targets= takes them: =((nil :maxlevel . 3) (org-agenda-files :tag . "project"))=. =""= offers headings to level 3 in every file. See [[file:04-outlines.org][Outlines]]. Mirrors =org-refile-targets=. |
235| =org-refile-use-outline-path= | string | ="file"= | How refile targets are written: =nil=, =t=, =file=, =full-file-path=, =buffer-name= or =title=. Mirrors =org-refile-use-outline-path=. |
236| =org-refile-allow-creating-parent-nodes= | string | ="nil"= | =t= or =confirm=: a refile target typed as =TARGET/New heading= adds the heading; =confirm= asks first. Mirrors =org-refile-allow-creating-parent-nodes=. |
233237| =org-agenda-files= | string | =""= | Files and folders the agenda reads, separated by =\n=; a file that isn't =.org= lists more, one per line. =""= reads the folders' files. See [[file:07-agenda.org][The agenda]]. Mirrors =org-agenda-files=. |
234238| =org-agenda-use-time-grid= | boolean | =true= | Grid lines at the times in =[org-agenda-time-grid]=, on the days it names. Mirrors =org-agenda-use-time-grid=. |
235239| =org-agenda-show-current-time-in-grid= | boolean | =true= | The now line on today's grid. Mirrors =org-agenda-show-current-time-in-grid=. |
@@ -520,6 +524,8 @@ Only variables whose names start with =org-=, =appt-=, =display-line-numbers=, =
520524| =org-agenda-sorting-strategy= | =[org-agenda-sorting-strategy]=: a list sets all four views; an alist sets =agenda=, =todo=, =tags= and =search=. A list with =user-defined-up= or =user-defined-down= isn't imported |
521525| =org-agenda-sort-notime-is-late=, =org-agenda-sort-noeffort-is-high=, =org-agenda-use-time-grid=, =org-agenda-show-current-time-in-grid= | The same key, as booleans |
522526| =org-agenda-custom-commands= | A =views.toml= view per command, named by its description, and per block a =[[view.block]]=. Types =agenda=, =alltodo=, =todo=, =tags=, =tags-todo=, =search= and =stuck=; settings =org-agenda-span=, =org-agenda-start-day=, =org-agenda-overriding-header=, =org-agenda-sorting-strategy=, =org-agenda-prefix-format= (a string) and =org-agenda-skip-function= as =org-agenda-skip-entry-if= or =org-agenda-skip-subtree-if=. Entries from =(add-to-list 'org-agenda-custom-commands …)= too. Other types, other settings and file lists aren't imported |
527| =org-refile-targets= | =org-refile-targets=, the value written as Lisp, when its files and specs are ones orgstar reads (not functions or variables) |
528| =org-refile-use-outline-path=, =org-refile-allow-creating-parent-nodes= | The symbol as a string |
523529| =org-stuck-projects= | =[org-stuck-projects]=: =match=, =todo=, =tags= and =regexp= from the four elements |
524530| =org-agenda-time-grid= | =[org-agenda-time-grid]=: =when= from the first element, =times= from the second; the strings are left out |
525531| =org-log-done=, =org-log-reschedule=, =org-log-redeadline= | The same key: =nil=, =time= (also =t=) or =note= |