Sources/OrgApp/RefileTargets.swift
285 lines · 14064 bytes
18 symbols in this file
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 = OrgPaths.expandingTilde(entry)
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}