Commit 6e240e443d

6e240e443d0dbd1f8df3f33fca3d9176f73d1b1f

parent: d85099bc95

Verified · cmc

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

columnview blocks: file: and ID sources, :match

The columnview dynamic block takes :id "file:PATH" (another file, relative to this one) and IDs in other agenda files (org-id-find), and :match filters entries as org-columns--capture-view does.

Closes #30

Layout: unified · split

Sources/OrgCore/Commands/ColumnView.swift +48 −11
@@ -260,8 +260,8 @@ public enum ColumnView {
260 /// summarized property org rewrites. 260 /// summarized property org rewrites.
261 /// Throws for an age operator's value that is neither a timestamp nor a duration. 261 /// Throws for an age operator's value that is neither a timestamp nor a duration.
262 public static func capture(text: String, tree: OrgTree, at offset: Int, global: Bool, format override: String? = nil, 262 public static func capture(text: String, tree: OrgTree, at offset: Int, global: Bool, format override: String? = nil,
263 maxLevel: Int? = nil, skipEmpty: Bool = false, excludeTags: [String] = [], now: Date = Date(), 263 maxLevel: Int? = nil, skipEmpty: Bool = false, excludeTags: [String] = [], match: String? = nil,
264 calendar: Calendar = .current) throws 264 now: Date = Date(), calendar: Calendar = .current) throws
265 -> (view: View, updates: [(start: Int, property: String, value: String)]) { 265 -> (view: View, updates: [(start: Int, property: String, value: String)]) {
266 let model = DocumentModel(tree: tree) 266 let model = DocumentModel(tree: tree)
267 let ns = text as NSString 267 let ns = text as NSString
@@ -335,11 +335,19 @@ public enum ColumnView {
335 } 335 }
336 } 336 }
337 } 337 }
338 // Rows. 338 // Rows. `:match` goes through `org-map-entries`, as a tags and property match.
339 var matches: ((Int) -> Bool)?
340 if let match, !match.isEmpty {
341 let matcher = TagsMatcher(match)
342 let source = AgendaSource(path: "", text: text, defaults: tree.settings, checksBlocking: false)
343 let byStart = Dictionary(source.headings.map { ($0.start, $0) }, uniquingKeysWith: { a, _ in a })
344 matches = { start in byStart[start].map { matcher.matches($0, in: source, now: now, calendar: calendar) } ?? false }
345 }
339 var rows: [Row] = [] 346 var rows: [Row] = []
340 for i in scope { 347 for i in scope {
341 let level = headings[i].level 348 let level = headings[i].level
342 if let maxLevel, level > maxLevel { continue } 349 if let maxLevel, level > maxLevel { continue }
350 if let matches, !matches(headings[i].headingRange.lowerBound) { continue }
343 let raw = specs.enumerated().map { column, spec -> String in 351 let raw = specs.enumerated().map { column, spec -> String in
344 summaries[i]?[column] ?? value(spec.property, heading: i, model: model, text: ns, clocksum: clocksum) 352 summaries[i]?[column] ?? value(spec.property, heading: i, model: model, text: ns, clocksum: clocksum)
345 } 353 }
@@ -394,24 +402,42 @@ extension EmacsBuffer {
394 let id = params.values[":id"] 402 let id = params.values[":id"]
395 var offset = begin 403 var offset = begin
396 var global = false 404 var global = false
405 // Another file's text and tree, for `file:` and IDs found elsewhere.
406 var source: (text: String, tree: OrgTree)?
397 if let id { 407 if let id {
398 switch id.symbol ?? id.string ?? "" { 408 switch id.symbol ?? id.string ?? id.description {
399 case "global": global = true 409 case "global": global = true
400 case "local", "nil", "": break 410 case "local", "nil", "": break
411 case let value where value.hasPrefix("file:"):
412 // `file:PATH`: the whole file, read from disk; relative to this file's folder.
413 var path = (String(value.dropFirst(5)) as NSString).expandingTildeInPath
414 if !path.hasPrefix("/"), let file = options.filePath { path = ((file as NSString).deletingLastPathComponent as NSString).appendingPathComponent(path) }
415 guard let text = path == options.filePath ? string : try? String(contentsOfFile: path, encoding: .utf8) else {
416 throw UserError(message: "No such file: \"\(value)\"")
417 }
418 if path != options.filePath { source = (text, OrgParser.parse(text)) }
419 global = true
401 case let value: 420 case let value:
402 if value.hasPrefix("file:") { throw UserError(message: "Column views of other files aren't supported yet") } 421 let pattern = "^[ \\t]*:ID:[ \\t]+" + NSRegularExpression.escapedPattern(for: value) + "[ \\t]*$"
403 guard let match = searchForwardFromStart("^[ \\t]*:ID:[ \\t]+" + NSRegularExpression.escapedPattern(for: value) + "[ \\t]*$") else { 422 if let match = searchForwardFromStart(pattern) {
423 offset = match
424 } else if let found = Self.findID(pattern, in: (options.agendaFiles ?? []).filter { $0 != options.filePath }) {
425 // `org-id-find`: another agenda file.
426 source = (found.text, OrgParser.parse(found.text))
427 offset = found.offset
428 } else {
404 throw UserError(message: "Cannot find entry with :ID: \(value)") 429 throw UserError(message: "Cannot find entry with :ID: \(value)")
405 } 430 }
406 offset = match
407 } 431 }
408 } 432 }
409 let hlines = params.values[":hlines"] 433 let hlines = params.values[":hlines"]
410 let excluded = params.values[":exclude-tags"]?.elements?.compactMap { $0.string ?? $0.symbol } ?? [] 434 let excluded = params.values[":exclude-tags"]?.elements?.compactMap { $0.string ?? $0.symbol } ?? []
411 let captured = try ColumnView.capture(text: string, tree: tree, at: offset, global: global, format: params.values[":format"]?.string, 435 let captured = try ColumnView.capture(text: source?.text ?? string, tree: source?.tree ?? tree, at: offset, global: global,
412 maxLevel: params.int(":maxlevel"), skipEmpty: params.flag(":skip-empty-rows"), 436 format: params.values[":format"]?.string, maxLevel: params.int(":maxlevel"),
413 excludeTags: excluded, now: now, calendar: calendar) 437 skipEmpty: params.flag(":skip-empty-rows"), excludeTags: excluded,
414 for update in captured.updates.sorted(by: { $0.start > $1.start }) { 438 match: params.values[":match"]?.string, now: now, calendar: calendar)
439 // Summaries go into this buffer's entries; another file's are left as they are.
440 for update in source == nil ? captured.updates.sorted(by: { $0.start > $1.start }) : [] {
415 point = update.start 441 point = update.start
416 entryPut(update.property, update.value) 442 entryPut(update.property, update.value)
417 } 443 }
@@ -424,6 +450,17 @@ extension EmacsBuffer {
424 return lines.joined(separator: "\n") 450 return lines.joined(separator: "\n")
425 } 451 }
426 452
453 /// The first of `paths` with a line matching `pattern`, its text and the line's start.
454 static func findID(_ pattern: String, in paths: [String]) -> (text: String, offset: Int)? {
455 guard let regex = try? NSRegularExpression(pattern: pattern, options: [.anchorsMatchLines, .caseInsensitive]) else { return nil }
456 for path in paths {
457 guard let text = try? String(contentsOfFile: path, encoding: .utf8),
458 let m = regex.firstMatch(in: text, range: NSRange(location: 0, length: (text as NSString).length)) else { continue }
459 return (text, m.range.location)
460 }
461 return nil
462 }
463
427 private func searchForwardFromStart(_ pattern: String) -> Int? { 464 private func searchForwardFromStart(_ pattern: String) -> Int? {
428 saveExcursion { 465 saveExcursion {
429 point = 0 466 point = 0
Tests/OrgCoreTests/ColumnEditTests.swift +83
@@ -106,3 +106,86 @@ struct ColumnEditTests {
106 #expect(Self.run(SetColumnValue(property: "TAGS", value: ":home:work:"), at: at).contains(":home:work:")) 106 #expect(Self.run(SetColumnValue(property: "TAGS", value: ":home:work:"), at: at).contains(":home:work:"))
107 } 107 }
108} 108}
109
110/// The `columnview` block's `:id` sources and `:match`, against Emacs visiting the files.
111struct ColumnViewSourceTests {
112 static let a = """
113 #+COLUMNS: %25ITEM %TODO %Effort{:}
114 #+BEGIN: columnview
115 #+END:
116 * Local :work:
117 :PROPERTIES:
118 :ID: local-one
119 :END:
120 ** TODO Child :home:
121 :PROPERTIES:
122 :Effort: 0:20
123 :END:
124 ** Other child :work:
125 :PROPERTIES:
126 :Effort: 0:40
127 :END:
128
129 """
130 static let b = """
131 #+COLUMNS: %ITEM %Owner %Effort{:}
132 * Bee project
133 :PROPERTIES:
134 :ID: bee-id
135 :END:
136 ** Task :work:
137 :PROPERTIES:
138 :Owner: Ada
139 :Effort: 1:00
140 :END:
141 * Elsewhere
142 :PROPERTIES:
143 :Owner: Bob
144 :END:
145
146 """
147
148 static let params = [
149 ":id \"file:b.org\"", ":id bee-id", ":id local-one", ":id global :match \"work\"", ":id global :match \"-home\" :maxlevel 2",
150 ":id \"file:b.org\" :match \"Owner=\\\"Ada\\\"\"", ":id local-one :match \"TODO=\\\"TODO\\\"\"",
151 ]
152
153 @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
154 func sourcesLikeOrg() throws {
155 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-colview-\(UUID().uuidString)").standardizedFileURL
156 defer { try? FileManager.default.removeItem(at: folder) }
157 try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
158 let aPath = folder.appendingPathComponent("a.org").path
159 let bPath = folder.appendingPathComponent("b.org").path
160 for param in Self.params {
161 let text = Self.a.replacingOccurrences(of: "#+BEGIN: columnview\n", with: "#+BEGIN: columnview \(param)\n")
162 try text.write(toFile: aPath, atomically: true, encoding: .utf8)
163 try Self.b.write(toFile: bPath, atomically: true, encoding: .utf8)
164 let form = """
165 (progn
166 (require 'org) (require 'org-colview) (require 'org-id)
167 (setq org-agenda-files (list "\(aPath)" "\(bPath)") org-id-locations-file "\(folder.path)/ids")
168 (find-file "\(aPath)")
169 (goto-char (point-min))
170 (re-search-forward "^#\\\\+BEGIN:")
171 (beginning-of-line)
172 (org-update-dblock)
173 (princ (buffer-string)))
174 """
175 let emacs = try EmacsOracle.run(["-Q", "--batch", "--eval", form], environment: ["TZ": "UTC"])
176 var options = EditingOptions.org
177 options.filePath = aPath
178 options.agendaFiles = [aPath, bPath]
179 let caret = (text as NSString).range(of: "#+BEGIN").location
180 let context = EditContext(revision: 0, text: text, tree: OrgParser.parse(text), selection: [caret..<caret], options: options)
181 var ours = text
182 switch UpdateDynamicBlock().run(in: context) {
183 case .commit(let result):
184 for edit in result.edits.sorted(by: { $0.range.lowerBound > $1.range.lowerBound }) { ours = edit.apply(to: ours) }
185 case .failed(let message): ours = "failed: \(message)"
186 default: ours = "other"
187 }
188 #expect(emacs.hasSuffix(ours), "\(param)\nours:\n\(ours)\nemacs:\n\(emacs)")
189 }
190 }
191}
docs/manual/guide/04-outlines.org +6 −3
@@ -711,7 +711,8 @@ takes these parameters:
711 711
712| Parameter | Meaning | 712| Parameter | Meaning |
713|--------------------+-------------------------------------------------------------------| 713|--------------------+-------------------------------------------------------------------|
714| =:id= | =local=, =global=, or an entry's =ID= | 714| =:id= | =local=, =global=, =file:PATH= (another file, all of it), or an entry's =ID= |
715| =:match= | keep entries matching a tag and property match, such as ="+work-home"= |
715| =:format= | a column format to use instead of the entry's or file's | 716| =:format= | a column format to use instead of the entry's or file's |
716| =:hlines= | =t= for a line between all rows, or N for one before each level N or higher row | 717| =:hlines= | =t= for a line between all rows, or N for one before each level N or higher row |
717| =:maxlevel= | leave out deeper headings | 718| =:maxlevel= | leave out deeper headings |
@@ -719,8 +720,10 @@ takes these parameters:
719| =:exclude-tags= | leave out entries with these tags, as a list | 720| =:exclude-tags= | leave out entries with these tags, as a list |
720| =:indent= | indent =ITEM= by level | 721| =:indent= | indent =ITEM= by level |
721 722
722Existing =#+TBLFM:= lines after the table are kept. An =:id= of the form =file:path= 723Existing =#+TBLFM:= lines after the table are kept. A =file:= path counts from this
723(another file) is not supported. 724file's folder. An =ID= is looked for in this file, then in the agenda files, as
725=org-id-find= does. For another file the table is built from the file on disk, and the
726summaries are not written into it; Org writes them into that file's buffer.
724 727
725* Footnotes 728* Footnotes
726 729