Capture table lines !133

merged merged by cmc on 2026-10-07 05:58 UTC · krz/orgstar:capture-table-line into main

4 files changed, +131 −7

Layout: unified · split

Sources/OrgApp/CaptureModel.swift +5 −3
@@ -9,7 +9,7 @@ import OrgDocument
99/// [[template]]
1010/// key = "t"
1111/// name = "Personal todo"
12/// type = "entry" # entry, item, checkitem or plain
12/// type = "entry" # entry, item, checkitem, plain or table-line
1313/// file = "todo.org" # relative to the first folder, or ~/… or /…
1414/// headline = "Inbox" # or olp = "Projects/Work"; neither for the end of the file
1515/// template = "* TODO %?\n%i\n%a"
@@ -19,7 +19,8 @@ import OrgDocument
1919/// Other targets: `datetree = true` (under `olp` if given; `tree-type` "day", "week" or
2020/// "month"), `id = "…"` without `file`, `clock = true` without `file`. Other properties, as
2121/// in `org-capture-templates`: `immediate-finish`, `empty-lines`, `empty-lines-before`,
22/// `empty-lines-after`, `jump-to-captured`, `clock-in`, `clock-keep`, `clock-resume`.
22/// `empty-lines-after`, `jump-to-captured`, `clock-in`, `clock-keep`, `clock-resume`,
23/// `table-line-pos`.
2324@MainActor
2425public enum CaptureTemplates {
2526 public static var userFile: URL { UserConfig.file("capture.toml") }
@@ -79,7 +80,8 @@ public enum CaptureTemplates {
7980 let options = CaptureTemplate.Options(
8081 prepend: flag("prepend"), immediateFinish: flag("immediate-finish"), emptyLines: lines("empty-lines"),
8182 emptyLinesBefore: lines("empty-lines-before"), emptyLinesAfter: lines("empty-lines-after"),
82 jumpToCaptured: flag("jump-to-captured"), clockIn: flag("clock-in"), clockKeep: flag("clock-keep"), clockResume: flag("clock-resume")
83 jumpToCaptured: flag("jump-to-captured"), clockIn: flag("clock-in"), clockKeep: flag("clock-keep"), clockResume: flag("clock-resume"),
84 tableLinePos: values["table-line-pos"]?.string
8385 )
8486 templates.append(CaptureTemplate(key: key, name: values["name"]?.string ?? key, kind: kind, target: target, template: body, options: options))
8587 }
Sources/OrgApp/EmacsImport.swift +3 −2
@@ -556,7 +556,7 @@ public struct EmacsImport: Sendable {
556556 unsupported.append(Note(id: id(), name: "capture \"\(key)\"", reason: "a template that isn't a string", source: source))
557557 return
558558 }
559 guard ["entry", "item", "checkitem", "plain"].contains(type) else {
559 guard ["entry", "item", "checkitem", "plain", "table-line"].contains(type) else {
560560 unsupported.append(Note(id: id(), name: "capture \"\(key)\"", reason: "\(type) templates aren't supported", source: source))
561561 return
562562 }
@@ -607,7 +607,8 @@ public struct EmacsImport: Sendable {
607607 for count in ["empty-lines", "empty-lines-before", "empty-lines-after"] {
608608 if let n = properties[":" + count]?.integer { toml += "\(count) = \(n)\n" }
609609 }
610 let ignored = properties.keys.filter { ![":prepend", ":immediate-finish", ":jump-to-captured", ":clock-in", ":clock-keep", ":clock-resume", ":empty-lines", ":empty-lines-before", ":empty-lines-after", ":tree-type"].contains($0) }
610 if let pos = properties[":table-line-pos"]?.string { toml += "table-line-pos = \(quoted(pos))\n" }
611 let ignored = properties.keys.filter { ![":prepend", ":immediate-finish", ":jump-to-captured", ":clock-in", ":clock-keep", ":clock-resume", ":empty-lines", ":empty-lines-before", ":empty-lines-after", ":tree-type", ":table-line-pos"].contains($0) }
611612 if !ignored.isEmpty {
612613 unsupported.append(Note(id: id(), name: "capture \"\(key)\"", reason: "\(ignored.sorted().joined(separator: ", ")) left out", source: source))
613614 }
Sources/OrgCore/Capture/Capture.swift +82 −2
@@ -4,7 +4,7 @@ import Foundation
44// target, as `org-capture` followed by `org-capture-finalize` leaves the target file.
55
66public struct CaptureTemplate: Sendable, Equatable, Identifiable {
7 public enum Kind: String, Sendable, Equatable { case entry, item, checkitem, plain }
7 public enum Kind: String, Sendable, Equatable { case entry, item, checkitem, plain, tableLine = "table-line" }
88
99 /// `:tree-type`: what a date tree groups entries by.
1010 public enum TreeType: String, Sendable, Equatable { case day, week, month }
@@ -46,11 +46,15 @@ public struct CaptureTemplate: Sendable, Equatable, Identifiable {
4646 public var clockIn = false
4747 public var clockKeep = false
4848 public var clockResume = false
49 /// `:table-line-pos`: `II-3` is the third line above the second rule.
50 public var tableLinePos: String?
4951
5052 public init(
5153 prepend: Bool = false, immediateFinish: Bool = false, emptyLines: Int? = nil, emptyLinesBefore: Int? = nil,
52 emptyLinesAfter: Int? = nil, jumpToCaptured: Bool = false, clockIn: Bool = false, clockKeep: Bool = false, clockResume: Bool = false
54 emptyLinesAfter: Int? = nil, jumpToCaptured: Bool = false, clockIn: Bool = false, clockKeep: Bool = false, clockResume: Bool = false,
55 tableLinePos: String? = nil
5356 ) {
57 self.tableLinePos = tableLinePos
5458 self.prepend = prepend
5559 self.immediateFinish = immediateFinish
5660 self.emptyLines = emptyLines
@@ -474,6 +478,7 @@ public enum Capture {
474478 case .entry: start = try placeEntry(text, options: options, heading: entryHeading, buffer)
475479 case .plain: start = placePlain(text, options: options, heading: entryHeading, buffer)
476480 case .item, .checkitem: start = try placeItem(text, checkbox: template.kind == .checkitem, options: options, heading: entryHeading, buffer)
481 case .tableLine: start = try placeTableLine(text, options: options, heading: entryHeading, buffer)
477482 }
478483 } catch let error as Failure {
479484 return .failure(error)
@@ -730,6 +735,81 @@ public enum Capture {
730735 return start
731736 }
732737
738 /// `org-capture-place-table-line`, then what `org-capture-finalize` does to the table: the
739 /// first table in the entry, or the file, gets the line, at its end, after its first rule
740 /// with `prepend`, or where `table-line-pos` says; a table is made when there's none.
741 static func placeTableLine(_ filled: String, options: CaptureTemplate.Options, heading: Int?, _ buffer: EmacsBuffer) throws -> Int {
742 let template = filled.trimmingCharacters(in: .whitespacesAndNewlines)
743 // `org-table-border-regexp`: a template that isn't a table line becomes one.
744 let text = template.range(of: "^[ \\t]*[^| \\t]", options: .regularExpression) != nil ? "| " + template : template + "\n"
745 var begin = 0
746 var end = buffer.length
747 if let heading {
748 begin = min(buffer.length, buffer.lineEnd(heading) + 1)
749 buffer.point = buffer.lineEnd(heading)
750 nextHeading(buffer)
751 end = buffer.point
752 }
753 var table: Range<Int>?
754 buffer.point = begin
755 while table == nil, let match = buffer.searchForward("^[ \\t]*\\|[^-]", bound: end, caseInsensitive: false) {
756 buffer.point = match[0]!.lowerBound
757 if buffer.atTable { table = buffer.tableBegin()..<buffer.tableEnd() } else { buffer.point = match[0]!.upperBound }
758 }
759 if table == nil {
760 buffer.point = end
761 if !buffer.bolp { buffer.insert("\n") }
762 let origin = buffer.point
763 buffer.insert("| |\n|---|\n")
764 table = origin..<buffer.point
765 }
766 let rows = buffer.substring(table!.lowerBound, table!.upperBound).components(separatedBy: "\n")
767 func lineStart(_ index: Int) -> Int {
768 buffer.saveExcursion {
769 buffer.point = table!.lowerBound
770 return buffer.forwardLine(index) == 0 ? min(buffer.point, table!.upperBound) : table!.upperBound
771 }
772 }
773 if let pos = options.tableLinePos {
774 guard let m = pos.firstMatch(of: /(I+)([-+][0-9]+)/) else { throw Failure.message("Invalid table line specification \"\(pos)\"") }
775 let hlines = rows.indices.filter { rows[$0].range(of: "^[ \\t]*\\|-", options: .regularExpression) != nil }
776 guard m.1.count <= hlines.count else { throw Failure.message("Invalid table line specification \"\(pos)\"") }
777 let delta = Int(m.2.replacingOccurrences(of: "+", with: ""))!
778 buffer.point = lineStart(hlines[m.1.count - 1] + delta + (delta < 0 ? 0 : -1) + 1)
779 } else if options.prepend {
780 if let rule = rows.firstIndex(where: { $0.range(of: "^[ \\t]*\\|-", options: .regularExpression) != nil }) {
781 let data = rows.indices.first { $0 > rule && rows[$0].range(of: "^[ \\t]*\\|[^-]", options: .regularExpression) != nil }
782 buffer.point = data.map(lineStart) ?? table!.upperBound
783 } else {
784 buffer.point = table!.lowerBound
785 }
786 } else {
787 buffer.point = table!.upperBound
788 }
789 if !buffer.bolp { buffer.insert("\n") }
790 let start = buffer.point
791 let lines = text.filter { $0 == "\n" }.count
792 buffer.insert(text)
793 // `org-capture-finalize`: align, or fix the formulas' row references and recalculate.
794 buffer.point = start
795 let row = buffer.substring(0, start).filter { $0 == "\n" }.count
796 if buffer.atTable {
797 if buffer.firstTblfm(after: buffer.tableEnd()) == nil {
798 buffer.tableAlign()
799 } else {
800 buffer.fixFormulas("@", replace: [:], limit: buffer.tableCurrentDataLine() - 1, delta: lines)
801 do {
802 try buffer.tableRecalculate(all: true)
803 } catch let unsupported as Calc.Unsupported {
804 throw Failure.message("The table's formulas need Emacs: \(unsupported.reason)")
805 }
806 }
807 }
808 buffer.point = 0
809 buffer.forwardLine(row)
810 return buffer.point
811 }
812
733813 /// `org-end-of-meta-data t`: past planning, drawers and the property drawer.
734814 static func skipMetaData(_ buffer: EmacsBuffer) {
735815 while buffer.point < buffer.length {
Tests/OrgCoreTests/CaptureTests.swift +41
@@ -28,6 +28,7 @@ struct CaptureTests {
2828 if let n = o.emptyLines { properties += " :empty-lines \(n)" }
2929 if let n = o.emptyLinesBefore { properties += " :empty-lines-before \(n)" }
3030 if let n = o.emptyLinesAfter { properties += " :empty-lines-after \(n)" }
31 if let pos = o.tableLinePos { properties += " :table-line-pos \(lisp(pos))" }
3132 switch c.template.target {
3233 case .file: target = "(file \(lisp(path)))"
3334 case .headline(_, let h): target = "(file+headline \(lisp(path)) \(lisp(h)))"
@@ -135,6 +136,46 @@ struct CaptureTests {
135136 }
136137 }
137138
139 static let tableFiles = [
140 "* Inbox\n| a | b |\n|---+---|\n| 1 | 2 |\n* Later\n",
141 "* Inbox\nText first.\n\n| a | b |\n|---+---|\n| 1 | 2 |\n|---+---|\n| total | |\n\nAfter.\n* Later\n",
142 "* Inbox\nNo table here.\n* Later\n",
143 "* Inbox\n",
144 "| x |\n| 1 |\n",
145 "* Inbox\n| n | sq |\n|---+----|\n| 2 | 4 |\n| 3 | 9 |\n#+TBLFM: $2=$1^2::@2$1=@3$1-1\n* Later\n",
146 ]
147
148 static let tableTemplates: [CaptureTemplate] = [
149 CaptureTemplate(key: "x", name: "", kind: .tableLine, target: .headline(file: "", headline: "Inbox"), template: "| %? | new |"),
150 CaptureTemplate(key: "x", name: "", kind: .tableLine, target: .headline(file: "", headline: "Inbox"), template: "| %? |", prepend: true),
151 CaptureTemplate(key: "x", name: "", kind: .tableLine, target: .headline(file: "", headline: "Inbox"), template: "%? | plain",
152 options: .init(tableLinePos: "II-1")),
153 CaptureTemplate(key: "x", name: "", kind: .tableLine, target: .headline(file: "", headline: "Inbox"), template: "| first %? |\n| second |",
154 options: .init(tableLinePos: "I+1")),
155 CaptureTemplate(key: "x", name: "", kind: .tableLine, target: .file(""), template: "| %? |"),
156 ]
157
158 @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
159 func tableLinesMatchEmacs() throws {
160 let seconds = 1_789_000_000
161 var cases: [Case] = []
162 for template in Self.tableTemplates {
163 for file in Self.tableFiles {
164 if case .headline = template.target, !file.contains("Inbox") { continue }
165 if template.options.tableLinePos == "II-1", !file.contains("total") { continue }
166 // Text in a computed column: Calc's symbolic result goes to Emacs.
167 if template.template.contains("first"), file.contains("TBLFM") { continue }
168 cases.append(Case(file: file, template: template, typed: "7"))
169 }
170 }
171 let emacs = try Self.emacs(cases, seconds: seconds)
172 let now = Date(timeIntervalSince1970: Double(seconds))
173 for (c, expected) in zip(cases, emacs) {
174 let mine = Self.ours(c, now: now)
175 #expect(mine == expected, "\(c.template.template.debugDescription) prepend \(c.template.prepend) pos \(c.template.options.tableLinePos ?? "-") into \(c.file.debugDescription)\nours:\n\(mine)\nemacs:\n\(expected)")
176 }
177 }
178
138179 static let datetreeFiles = [
139180 "",
140181 "#+TITLE: Journal\n",