Commit a81466b635

a81466b635dcb01c9617cb6b5572f5bed45963b9

parent: d49c433249

Verified · cmc

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

#+PLOT

- TablePlot ports org-plot: option parsing with its quirks, the table (header labels, transpose, time and text ind columns), the data and grid data files and the gnuplot script; oracle-tested against org-plot/gnuplot with gnuplot stubbed.
- PlotChart (Swift Charts): 2d as lines/points/bars/impulses/steps, grid as a heat map, 3d as a surface (wireframe in files); PlotOutput writes PNG/JPEG/PDF and, on the Mac, runs gnuplot when installed.
- Plot Table (app.plot, C-c " g) on the Mac (sheet or file) and iOS (More › Table, Commands).
- Doom preset: keys with a double quote are escaped in the generated TOML.
- gnuplot isn't installed on this machine, so the gnuplot run itself is untested beyond its script.

Closes #38

Layout: unified · split

Sources/OrgApp/PlotChart.swift added +301
@@ -0,0 +1,301 @@
1import Charts
2import Foundation
3import OrgCore
4import SwiftUI
5
6/// A `#+PLOT` table drawn by Swift Charts, as gnuplot would draw it for org-plot: 2d as lines,
7/// points, bars or impulses per `with:`, grid as a heat map, 3d as a surface (seen from above
8/// with `map:t`). `still` draws 3d as a wireframe, which an image can hold.
9public struct PlotChart: View {
10 let plot: TablePlot.Plot
11 let still: Bool
12
13 public init(_ plot: TablePlot.Plot, still: Bool = false) {
14 self.plot = plot
15 self.still = still
16 }
17
18 public var body: some View {
19 VStack(spacing: 8) {
20 if let title = plot.options.title { Text(title).font(.headline) }
21 switch plot.options.type {
22 case "grid": HeatMap(plot: plot)
23 case "3d" where plot.options["map"]?.truthy == true: HeatMap(plot: plot)
24 case "3d" where still: Wireframe(values: TablePlot.matrix(plot).values)
25 case "3d": Surface(plot: plot)
26 default: Lines(plot: plot)
27 }
28 }
29 .padding()
30 }
31
32 /// The `ymin`/`ymax` (or `xmin`/`xmax`) range, filling in from `values` what isn't given.
33 static func domain(_ low: TablePlot.Value?, _ high: TablePlot.Value?, values: [Double]) -> ClosedRange<Double>? {
34 func number(_ v: TablePlot.Value?) -> Double? { if case .number(let n)? = v { n } else { nil } }
35 guard number(low) != nil || number(high) != nil else { return nil }
36 let lower = number(low) ?? values.min() ?? 0
37 let upper = number(high) ?? values.max() ?? lower + 1
38 return lower < upper ? lower...upper : nil
39 }
40
41 struct Lines: View {
42 let plot: TablePlot.Plot
43
44 var body: some View {
45 let series = TablePlot.series(plot)
46 let o = plot.options
47 let ys = series.flatMap { $0.points.map(\.y) }
48 let xs = series.flatMap { $0.points.compactMap { if case .number(let n) = $0.x { n } else { nil } } }
49 let ticks = o["ticks"].flatMap { if case .number(let n) = $0 { Int(n) } else { nil } }
50 let numericX = series.allSatisfy { $0.points.allSatisfy { if case .number = $0.x { true } else { false } } }
51 let bars = ["boxes", "histograms", "hist", "impulses"].contains(o.with)
52 let chart = Chart {
53 ForEach(Array(series.enumerated()), id: \.offset) { _, s in
54 ForEach(Array(s.points.enumerated()), id: \.offset) { _, point in
55 mark(point.x, point.y, series: s.label)
56 }
57 }
58 }
59 .chartYAxis { AxisMarks(values: .automatic(desiredCount: ticks ?? 5)) }
60 .chartLegend(series.count > 1 ? .visible : .hidden)
61 // As gnuplot autoscales: to the data, from zero for bars.
62 let y = Group {
63 if let domain = PlotChart.domain(o["ymin"], o["ymax"], values: ys) {
64 chart.chartYScale(domain: domain)
65 } else {
66 chart.chartYScale(domain: .automatic(includesZero: bars))
67 }
68 }
69 if numericX, let domain = PlotChart.domain(o["xmin"], o["xmax"], values: xs) {
70 y.chartXScale(domain: domain)
71 } else if numericX {
72 y.chartXScale(domain: .automatic(includesZero: false))
73 } else {
74 y
75 }
76 }
77
78 @ChartContentBuilder
79 func mark(_ x: TablePlot.Series.X, _ y: Double, series: String) -> some ChartContent {
80 switch x {
81 case .number(let n): marks(.value("x", n), y, series)
82 case .date(let d): marks(.value("x", d), y, series)
83 case .label(let l): marks(.value("x", l), y, series)
84 }
85 }
86
87 @ChartContentBuilder
88 func marks<X: Plottable>(_ x: PlottableValue<X>, _ y: Double, _ series: String) -> some ChartContent {
89 switch plot.options.with {
90 case "points", "dots":
91 PointMark(x: x, y: .value("y", y)).foregroundStyle(by: .value("Series", series))
92 case "linespoints":
93 LineMark(x: x, y: .value("y", y)).foregroundStyle(by: .value("Series", series)).symbol(by: .value("Series", series))
94 case "impulses":
95 BarMark(x: x, y: .value("y", y), width: 2).foregroundStyle(by: .value("Series", series))
96 case "boxes", "histograms", "hist":
97 BarMark(x: x, y: .value("y", y)).foregroundStyle(by: .value("Series", series)).position(by: .value("Series", series))
98 case "steps":
99 LineMark(x: x, y: .value("y", y)).foregroundStyle(by: .value("Series", series)).interpolationMethod(.stepEnd)
100 case "fsteps":
101 LineMark(x: x, y: .value("y", y)).foregroundStyle(by: .value("Series", series)).interpolationMethod(.stepStart)
102 default:
103 LineMark(x: x, y: .value("y", y)).foregroundStyle(by: .value("Series", series))
104 }
105 }
106 }
107
108 struct HeatMap: View {
109 let plot: TablePlot.Plot
110
111 var body: some View {
112 let (values, rowLabels) = TablePlot.matrix(plot)
113 let columnLabels = columnNames(values.first?.count ?? 0)
114 Chart {
115 ForEach(Array(values.enumerated()), id: \.offset) { r, row in
116 ForEach(Array(row.enumerated()), id: \.offset) { c, value in
117 RectangleMark(x: .value("Column", columnLabels[c]), y: .value("Row", rowName(r, rowLabels)),
118 width: .ratio(1), height: .ratio(1))
119 .foregroundStyle(by: .value("Value", value))
120 }
121 }
122 }
123 .chartForegroundStyleScale(range: Gradient(colors: [.indigo, .teal, .yellow]))
124 // The first row at the bottom, as gnuplot draws it.
125 .chartYScale(domain: values.indices.reversed().map { rowName($0, rowLabels) })
126 .chartXScale(domain: columnLabels)
127 }
128
129 func rowName(_ r: Int, _ labels: [String]) -> String { r < labels.count ? labels[r] : "\(r + 1)" }
130
131 /// The header's names for the plotted columns, or their numbers.
132 func columnNames(_ count: Int) -> [String] {
133 let ind = plot.options.ind - 1
134 let header = plot.options.labels ?? []
135 var deps = plot.options.deps.map { $0.map { $0 - 1 } } ?? Array(0..<plot.columns)
136 deps.removeAll { $0 == ind }
137 return (0..<count).map { i in i < deps.count && deps[i] < header.count ? header[deps[i]] : "\(i + 1)" }
138 }
139 }
140
141 struct Surface: View {
142 let plot: TablePlot.Plot
143
144 var body: some View {
145 let values = TablePlot.matrix(plot).values
146 let rows = max(1, values.count), columns = max(1, values.first?.count ?? 1)
147 Chart3D {
148 SurfacePlot(x: "Column", y: "Value", z: "Row") { x, z in Self.interpolate(values, x, z) }
149 }
150 .chartXScale(domain: 1...Double(max(2, columns)))
151 .chartZScale(domain: 1...Double(max(2, rows)))
152 }
153
154 /// The matrix's value at a fractional column and row, from its four neighbours.
155 static func interpolate(_ m: [[Double]], _ x: Double, _ z: Double) -> Double {
156 guard !m.isEmpty, !m[0].isEmpty else { return 0 }
157 let c = min(max(x - 1, 0), Double(m[0].count - 1)), r = min(max(z - 1, 0), Double(m.count - 1))
158 let c0 = Int(c), r0 = Int(r), c1 = min(c0 + 1, m[0].count - 1), r1 = min(r0 + 1, m.count - 1)
159 func at(_ r: Int, _ c: Int) -> Double { c < m[r].count ? m[r][c] : 0 }
160 let fc = c - Double(c0), fr = r - Double(r0)
161 let top = at(r0, c0) * (1 - fc) + at(r0, c1) * fc
162 let bottom = at(r1, c0) * (1 - fc) + at(r1, c1) * fc
163 return top * (1 - fr) + bottom * fr
164 }
165 }
166}
167
168/// A matrix as gnuplot's `splot … matrix with lines` draws it: a wireframe seen from its
169/// default view, rows and columns along the floor and values up.
170struct Wireframe: View {
171 let values: [[Double]]
172
173 var body: some View {
174 Canvas { context, size in
175 let rows = values.count, columns = values.map(\.count).max() ?? 0
176 guard rows > 0, columns > 0 else { return }
177 let all = values.flatMap { $0 }
178 let low = all.min() ?? 0, high = max(all.max() ?? 1, low + 1e-9)
179 // gnuplot's view: 60° from the vertical, 30° around.
180 let rotation = 30.0 * .pi / 180, tilt = 60.0 * .pi / 180
181 func project(_ c: Double, _ r: Double, _ v: Double) -> CGPoint {
182 let x = c / Double(max(1, columns - 1)) - 0.5, y = r / Double(max(1, rows - 1)) - 0.5, z = (v - low) / (high - low) - 0.5
183 let px = x * cos(rotation) - y * sin(rotation)
184 let depth = x * sin(rotation) + y * cos(rotation)
185 let py = z * sin(tilt) - depth * cos(tilt)
186 let scale = min(size.width, size.height) * 0.75
187 return CGPoint(x: size.width / 2 + px * scale, y: size.height / 2 - py * scale)
188 }
189 var path = Path()
190 for r in 0..<rows {
191 for c in 0..<values[r].count {
192 let p = project(Double(c), Double(r), values[r][c])
193 if c == 0 { path.move(to: p) } else { path.addLine(to: p) }
194 }
195 }
196 for c in 0..<columns {
197 var started = false
198 for r in 0..<rows where c < values[r].count {
199 let p = project(Double(c), Double(r), values[r][c])
200 if started { path.addLine(to: p) } else { path.move(to: p); started = true }
201 }
202 }
203 context.stroke(path, with: .color(.accentColor), lineWidth: 1.5)
204 var floor = Path()
205 for (c, r) in [(0.0, 0.0), (Double(columns - 1), 0), (Double(columns - 1), Double(rows - 1)), (0, Double(rows - 1)), (0, 0)] {
206 let p = project(c, r, low)
207 if c == 0, r == 0, floor.isEmpty { floor.move(to: p) } else { floor.addLine(to: p) }
208 }
209 context.stroke(floor, with: .color(.secondary), lineWidth: 0.5)
210 }
211 }
212}
213
214/// Plots written to files and run through gnuplot.
215@MainActor
216public enum PlotOutput {
217 public struct Failure: Error, CustomStringConvertible {
218 public let description: String
219 }
220
221 /// `file:` relative to the Org file's folder.
222 public static func file(_ plot: TablePlot.Plot, directory: URL?) -> URL? {
223 guard let name = plot.options.file, !name.isEmpty else { return nil }
224 let expanded = (name as NSString).expandingTildeInPath
225 return expanded.hasPrefix("/") ? URL(fileURLWithPath: expanded) : (directory ?? URL(fileURLWithPath: NSHomeDirectory())).appendingPathComponent(expanded)
226 }
227
228 /// The chart as gnuplot's default 640×480, as PNG, JPEG or PDF by the file's extension.
229 public static func write(_ plot: TablePlot.Plot, to url: URL) throws {
230 let renderer = ImageRenderer(content: PlotChart(plot, still: true).frame(width: 640, height: 480).background(Color.white).environment(\.colorScheme, .light))
231 renderer.scale = 2
232 try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)
233 switch url.pathExtension.lowercased() {
234 case "pdf":
235 var box = CGRect(x: 0, y: 0, width: 640, height: 480)
236 guard let consumer = CGDataConsumer(url: url as CFURL), let context = CGContext(consumer: consumer, mediaBox: &box, nil) else {
237 throw Failure(description: "Can't write \(url.lastPathComponent)")
238 }
239 renderer.render { _, draw in
240 context.beginPDFPage(nil)
241 draw(context)
242 context.endPDFPage()
243 context.closePDF()
244 }
245 case "png", "jpg", "jpeg", "":
246 guard let image = renderer.cgImage else { throw Failure(description: "The plot couldn't be drawn") }
247 let type = ["jpg", "jpeg"].contains(url.pathExtension.lowercased()) ? "public.jpeg" : "public.png"
248 guard let destination = CGImageDestinationCreateWithURL(url as CFURL, type as CFString, 1, nil) else {
249 throw Failure(description: "Can't write \(url.lastPathComponent)")
250 }
251 CGImageDestinationAddImage(destination, image, nil)
252 guard CGImageDestinationFinalize(destination) else { throw Failure(description: "Can't write \(url.lastPathComponent)") }
253 default:
254 throw Failure(description: "Without gnuplot, plots are written as .png, .jpg or .pdf, not .\(url.pathExtension)")
255 }
256 }
257
258 #if os(macOS)
259 /// gnuplot on the `PATH` Babel uses, when installed.
260 public static var gnuplot: URL? {
261 let path = BabelRunner.environment["PATH"] ?? "/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin"
262 return path.split(separator: ":").map { URL(fileURLWithPath: String($0)).appendingPathComponent("gnuplot") }
263 .first { FileManager.default.isExecutableFile(atPath: $0.path) }
264 }
265
266 /// `org-plot/gnuplot` through gnuplot: the data file and script org-plot writes, run with
267 /// the output at `file:`, or a PNG for showing when there's none. Returns the image.
268 public static func runGnuplot(_ plot: TablePlot.Plot, directory: URL?, gnuplot: URL) async throws -> URL {
269 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-plot-\(UUID().uuidString)")
270 try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
271 let dataFile = folder.appendingPathComponent("data.tsv")
272 var plot = plot
273 let output = file(plot, directory: directory) ?? folder.appendingPathComponent("plot.png")
274 if plot.options.file == nil { plot.options.values["file"] = .string(output.path) }
275 let (data, labels): (String, [(Int, String)]) = plot.options.type == "grid" ? TablePlot.gridData(plot) : (TablePlot.data(plot), [])
276 try data.write(to: dataFile, atomically: true, encoding: .utf8)
277 var script = TablePlot.script(plot, dataFile: dataFile.path, output: output.path, yLabels: labels)
278 if let custom = plot.options["script"]?.description {
279 let path = (custom as NSString).expandingTildeInPath
280 let url = path.hasPrefix("/") ? URL(fileURLWithPath: path) : (directory ?? folder).appendingPathComponent(path)
281 guard let text = try? String(contentsOf: url, encoding: .utf8) else { throw Failure(description: "Can't read \(custom)") }
282 script = TablePlot.script(plot, dataFile: dataFile.path, output: output.path, yLabels: labels, preface: true)
283 + "\n" + text.replacingOccurrences(of: "$datafile", with: dataFile.path)
284 }
285 let scriptFile = folder.appendingPathComponent("plot.gp")
286 try script.write(to: scriptFile, atomically: true, encoding: .utf8)
287 let process = Process()
288 process.executableURL = gnuplot
289 process.arguments = [scriptFile.path]
290 process.currentDirectoryURL = directory
291 let errors = Pipe()
292 process.standardError = errors
293 try process.run()
294 while process.isRunning { try await Task.sleep(for: .milliseconds(50)) }
295 guard process.terminationStatus == 0 else {
296 throw Failure(description: "gnuplot: " + String(decoding: errors.fileHandleForReading.readDataToEndOfFile(), as: UTF8.self).trimmingCharacters(in: .whitespacesAndNewlines))
297 }
298 return output
299 }
300 #endif
301}
Sources/OrgCore/Compute/TablePlot.swift added +351
@@ -0,0 +1,351 @@
1import Foundation
2
3/// `#+PLOT` (org-plot.el, Org 9.8.7): the options above a table, the table as org-plot reads
4/// it, the data file and the gnuplot script `org-plot/gnuplot` writes, and the values a chart
5/// of its own draws.
6public enum TablePlot {
7 /// A value as `read-from-string` reads an option.
8 public enum Value: Sendable, Equatable, CustomStringConvertible {
9 case number(Double)
10 case symbol(String)
11 case string(String)
12 case list([Value])
13
14 public var description: String {
15 switch self {
16 case .number(let n): n == n.rounded() && abs(n) < 1e15 ? String(Int(n)) : String(n)
17 case .symbol(let s), .string(let s): s
18 case .list(let l): "(" + l.map(\.description).joined(separator: " ") + ")"
19 }
20 }
21
22 var int: Int? { if case .number(let n) = self { Int(n) } else { nil } }
23 public var truthy: Bool { if case .symbol(let s) = self { s != "nil" } else { true } }
24 }
25
26 /// The plist org-plot builds, by key without the colon.
27 public struct Options: Sendable, Equatable {
28 public var values: [String: Value] = [:]
29 /// `:set` and `:line`, latest first, as `cons` leaves them.
30 public var sets: [String] = []
31 public var lines: [String] = []
32
33 public subscript(key: String) -> Value? { values[key] }
34 public var type: String { values["plot-type"]?.description ?? "2d" }
35 public var with: String { values["with"]?.description ?? "lines" }
36 public var ind: Int { values["ind"]?.int ?? 0 }
37 public var deps: [Int]? {
38 guard case .list(let l)? = values["deps"] else { return nil }
39 return l.compactMap(\.int)
40 }
41 public var labels: [String]? {
42 guard case .list(let l)? = values["labels"] else { return nil }
43 return l.map(\.description)
44 }
45 public var file: String? { values["file"]?.description }
46 public var title: String? { values["title"]?.description }
47 }
48
49 static let keys: [(name: String, key: String)] = [
50 ("type", "plot-type"), ("script", "script"), ("line", "line"), ("set", "set"), ("title", "title"), ("ind", "ind"),
51 ("deps", "deps"), ("with", "with"), ("file", "file"), ("labels", "labels"), ("map", "map"), ("timeind", "timeind"),
52 ("timefmt", "timefmt"), ("min", "ymin"), ("ymin", "ymin"), ("max", "ymax"), ("ymax", "ymax"), ("xmin", "xmin"),
53 ("xmax", "xmax"), ("ticks", "ticks"), ("trans", "transpose"), ("transpose", "transpose"),
54 ]
55
56 /// `org-plot/add-options-to-plist`, with its quirks: a key also matches inside a longer
57 /// word (`timeind:` sets `ind`), and an unquoted value ends at `.`, `,` or `;`.
58 static func add(_ text: String, to options: inout Options) {
59 let value = #":("[^"]+?"|\([^)]+?\)|[^ \t\n\r;,.]*)"#
60 var start = text.startIndex
61 for (name, key) in keys {
62 let pattern = try! NSRegularExpression(pattern: NSRegularExpression.escapedPattern(for: name) + value)
63 if name == "set" || name == "line" {
64 while let m = pattern.firstMatch(in: text, range: NSRange(start..<text.endIndex, in: text)) {
65 start = Range(m.range, in: text)!.upperBound
66 let read = Self.read(String(text[Range(m.range(at: 1), in: text)!]))
67 if name == "set" { options.sets.insert(read.description, at: 0) } else { options.lines.insert(read.description, at: 0) }
68 }
69 } else if let m = pattern.firstMatch(in: text, range: NSRange(text.startIndex..., in: text)) {
70 options.values[key] = Self.read(String(text[Range(m.range(at: 1), in: text)!]))
71 }
72 }
73 }
74
75 /// `read-from-string` of an option's value.
76 static func read(_ s: String) -> Value {
77 if s.hasPrefix("\""), s.hasSuffix("\""), s.count >= 2 { return .string(String(s.dropFirst().dropLast())) }
78 if s.hasPrefix("("), s.hasSuffix(")") {
79 let inner = s.dropFirst().dropLast()
80 var items: [Value] = []
81 for m in inner.matches(of: /"[^"]*"|[^\s"]+/) { items.append(read(String(m.0))) }
82 return .list(items)
83 }
84 if let n = Double(s), s.range(of: "^[-+]?([0-9]+\\.?[0-9]*|\\.[0-9]+)(e[-+]?[0-9]+)?$", options: .regularExpression) != nil { return .number(n) }
85 return .symbol(s)
86 }
87
88 // MARK: - The table
89
90 /// What `org-plot/gnuplot` reads: the options, the header row as labels, and the rows.
91 public struct Plot: Sendable, Equatable {
92 public var options: Options
93 /// Rows of fields; nil for a rule left in the table.
94 public var rows: [[String]?]
95 public var columns: Int
96 /// The ind column holds timestamps (`:timeind`) or text (`:textind`).
97 public var timeInd = false
98 public var textInd = false
99 }
100
101 public struct Failure: Error, Equatable, CustomStringConvertible {
102 public let description: String
103 }
104
105 /// The plot for the table at `offset`, or the first table after it, with the `#+PLOT`
106 /// lines above it.
107 public static func plot(_ text: String, at offset: Int) throws -> Plot {
108 let buffer = EmacsBuffer(text, point: offset)
109 // `org-plot/goto-nearest-table`.
110 buffer.point = buffer.lineStart(buffer.point)
111 while !buffer.atTable, buffer.forwardLine(1) == 0 {}
112 guard buffer.atTable else { throw Failure(description: "No table at point") }
113 let begin = buffer.tableBegin()
114 var options = Options()
115 options.values = ["plot-type": .symbol("2d"), "with": .symbol("lines"), "ind": .number(0)]
116 func collect() {
117 buffer.point = begin
118 while buffer.forwardLine(-1) == 0, buffer.looking("[ \\t]*#\\+", caseInsensitive: false, setsMatch: false) != nil {
119 let line = buffer.substring(buffer.point, buffer.lineEnd(buffer.point))
120 if let m = line.firstMatch(of: /#\+PLOT: +(.*)$/) { add(String(m.1), to: &options) }
121 }
122 }
123 collect()
124 buffer.point = begin
125 var table = buffer.tableToLisp()
126 if let t = options["transpose"]?.description, ["y", "yes", "t"].contains(t) {
127 let rows = table.compactMap { $0 }
128 let width = rows.map(\.count).min() ?? 0
129 var transposed: [[String]?] = (0..<width).map { c in rows.map { $0[c] } }
130 if table.contains(where: { $0 == nil }), !transposed.isEmpty { transposed.insert(nil, at: 1) }
131 table = transposed
132 }
133 let first = table.first.flatMap { $0 } ?? (table.count > 1 ? table[1] : nil)
134 let columns = first?.count ?? 0
135 guard ["2d", "3d", "grid"].contains(options.type) else {
136 throw Failure(description: options.type == "radar" ? "Radar plots need gnuplot" : "Org-plot type `\(options.type)' is undefined")
137 }
138 if table.count > 1, table[1] == nil, let header = table[0] {
139 options.values["labels"] = .list(header.map { .string($0) })
140 table = table.dropFirst().filter { $0 != nil }
141 }
142 collect()
143 var plot = Plot(options: options, rows: table, columns: columns)
144 if options.type == "2d" {
145 let ind = options.ind - 1
146 if ind >= 0 {
147 let column = table.compactMap { $0 }.map { ind < $0.count ? $0[ind] : "" }
148 if column.allSatisfy({ $0.range(of: EmacsBuffer.timestampPattern, options: .regularExpression) != nil }) {
149 plot.timeInd = true
150 } else if options.with == "hist" || !column.allSatisfy(isNumber) {
151 plot.textInd = true
152 }
153 }
154 }
155 return plot
156 }
157
158 /// `org-table-number-regexp`.
159 static let numberPattern = "^([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%:]*|[<>]?[-+]?0[xX][0-9a-fA-F.]+|[<>]?[-+]?[0-9]+#[0-9a-zA-Z.]+|nan|[-+u]?inf)$"
160 static func isNumber(_ s: String) -> Bool { s.range(of: numberPattern, options: .regularExpression) != nil }
161
162 // MARK: - gnuplot
163
164 /// `org-plot/gnuplot-to-data`: tab-separated fields, numbers as they are, timestamps in
165 /// `timefmt`, other text quoted.
166 public static func data(_ plot: Plot, calendar: Calendar = .current) -> String {
167 let format = plot.options["timefmt"]?.description ?? "%Y-%m-%d-%H:%M:%S"
168 return plot.rows.compactMap { $0 }.map { row in
169 row.map { field -> String in
170 if isNumber(field) { return field }
171 if let m = field.firstMatch(of: try! Regex(EmacsBuffer.timestampPattern)),
172 let stamp = Timestamp.parse(String(field[m.range])) {
173 return strftime(format, stamp.start, calendar: calendar)
174 }
175 return "\"" + field.replacingOccurrences(of: "\"", with: "\"\"") + "\""
176 }.joined(separator: "\t")
177 }.joined(separator: "\n")
178 }
179
180 /// `format-time-string` for the escapes timestamps use.
181 static func strftime(_ format: String, _ p: Timestamp.Point, calendar: Calendar) -> String {
182 var out = ""
183 var chars = Array(format)
184 var i = 0
185 chars.append(" ")
186 while i < chars.count - 1 {
187 if chars[i] == "%" {
188 switch chars[i + 1] {
189 case "Y": out += String(format: "%04d", p.year)
190 case "m": out += String(format: "%02d", p.month)
191 case "d": out += String(format: "%02d", p.day)
192 case "H": out += String(format: "%02d", p.hour ?? 0)
193 case "M": out += String(format: "%02d", p.minute ?? 0)
194 case "S": out += "00"
195 case "%": out += "%"
196 default: out += "%" + String(chars[i + 1])
197 }
198 i += 2
199 } else {
200 out.append(chars[i])
201 i += 1
202 }
203 }
204 return out
205 }
206
207 /// `org-plot/gnuplot-to-grid-data`: each cell as the four corners gnuplot's `pm3d`
208 /// draws, and the ind column's values as y labels.
209 public static func gridData(_ plot: Plot) -> (data: String, yLabels: [(Int, String)]) {
210 let ind = plot.options.ind - 1
211 var rows = plot.rows.compactMap { $0 }
212 var labels: [(Int, String)] = []
213 if ind >= 0 { labels = rows.enumerated().map { ($0.offset + 1, ind < $0.element.count ? $0.element[ind] : "") } }
214 var deps = plot.options.deps.map { $0.map { $0 - 1 } } ?? Array((0..<(rows.first?.count ?? 0)).reversed())
215 if ind >= 0 || !deps.isEmpty {
216 deps.removeAll { $0 == ind }
217 rows = rows.map { row in row.indices.filter(deps.contains).map { row[$0] } }
218 }
219 var out = ""
220 let columns = rows.first?.count ?? 0
221 func corners(_ col: Int, _ row: Int, _ value: Double) -> String {
222 String(format: "%f %f %f\n%f %f %f\n", Double(col + 1), Double(row + 1) - 0.5, value, Double(col + 1), Double(row + 1) + 0.5, value)
223 }
224 for col in 0..<columns {
225 var back = "", front = ""
226 for (r, row) in rows.enumerated() {
227 let value = col < row.count ? stringToNumber(row[col]) : 0
228 back += corners(col - 1, r, value)
229 front += corners(col, r, value)
230 }
231 out += back + "\n" + front + "\n"
232 }
233 return (out, labels)
234 }
235
236 /// `string-to-number`: the leading number, else 0.
237 static func stringToNumber(_ s: String) -> Double {
238 let trimmed = s.drop { $0 == " " || $0 == "\t" }
239 guard let m = trimmed.firstMatch(of: /^[-+]?([0-9]+\.?[0-9]*|\.[0-9]+)([eE][-+]?[0-9]+)?/) else { return 0 }
240 return Double(m.0) ?? 0
241 }
242
243 /// `org-plot/gnuplot-script`, with `org-plot/gnuplot-term-extra` and the preamble empty.
244 /// `output` is where `file:` goes, expanded. A `preface` leaves out the plot command, for
245 /// a `script:` file to follow.
246 public static func script(_ plot: Plot, dataFile: String, output: String?, yLabels: [(Int, String)] = [], preface: Bool = false) -> String {
247 let o = plot.options
248 var script = "reset"
249 func add(_ line: String?) { if let line { script += "\n" + line } }
250 add("set term \(o.file.map { ($0 as NSString).pathExtension } ?? "GNUTERM") ")
251 if let output { add("set output '\(output)'") }
252 switch o.type {
253 case "3d": if o["map"]?.truthy == true { add("set map") }
254 case "grid": add(o["map"]?.truthy == true ? "set pm3d map" : "set map")
255 default: break
256 }
257 add("")
258 if let title = o.title { add("set title '\(title)'") }
259 for line in o.lines { add(line) }
260 for set in o.sets { add("set \(set)") }
261 if script.range(of: "(?m)^set datafile separator", options: .regularExpression) == nil { add("set datafile separator \"\\t\"") }
262 if !yLabels.isEmpty { add("set ytics (" + yLabels.map { "\"\($0.1)\" \($0.0)" }.joined(separator: ", ") + ")") }
263 if o["timeind"]?.truthy == true || plot.timeInd {
264 add("set xdata time")
265 add("set timefmt \"" + (o["timefmt"]?.description ?? "%Y-%m-%d-%H:%M:%S") + "\"")
266 }
267 if preface { return script }
268 var plotLines: [String] = []
269 let with = o.type == "grid" ? "pm3d" : o.with
270 switch o.type {
271 case "2d":
272 let ind = o.ind
273 let textInd = plot.textInd || o.with == "histograms"
274 for col in 0..<plot.columns {
275 if ind == col + 1 || (o.deps.map { !$0.contains(col + 1) } ?? false) { continue }
276 let using = ind > 0 && !textInd ? "\(ind):" : ""
277 let tic = textInd ? ":xticlabel(\(ind))" : ""
278 let label = o.labels.flatMap { col < $0.count ? $0[col] : nil } ?? "\(col + 1)"
279 plotLines.append("'\(dataFile)' using \(using)\(col + 1)\(tic) with \(with) title '\(label)'")
280 }
281 add("plot " + plotLines.joined(separator: ",\\\n "))
282 case "3d":
283 add("splot '\(dataFile)' matrix with \(with) title ''")
284 default:
285 add("splot '\(dataFile)' with \(with) title ''")
286 }
287 return script
288 }
289
290 // MARK: - Values for a chart
291
292 /// A dependent column's points: x as a number, a date or a label, and y.
293 public struct Series: Sendable, Equatable {
294 public enum X: Sendable, Equatable {
295 case number(Double)
296 case date(Date)
297 case label(String)
298 }
299 public var label: String
300 public var points: [(x: X, y: Double)]
301 public static func == (a: Series, b: Series) -> Bool {
302 a.label == b.label && a.points.count == b.points.count && zip(a.points, b.points).allSatisfy { $0.x == $1.x && $0.y == $1.y }
303 }
304 }
305
306 /// The 2d plot's series, as the script plots them: one per column but the ind column (or
307 /// the deps), against the ind column or the row number.
308 public static func series(_ plot: Plot, calendar: Calendar = .current) -> [Series] {
309 let o = plot.options
310 let rows = plot.rows.compactMap { $0 }
311 let ind = o.ind
312 var out: [Series] = []
313 for col in 0..<plot.columns {
314 if ind == col + 1 || (o.deps.map { !$0.contains(col + 1) } ?? false) { continue }
315 let label = o.labels.flatMap { col < $0.count ? $0[col] : nil } ?? "\(col + 1)"
316 var points: [(Series.X, Double)] = []
317 for (r, row) in rows.enumerated() {
318 guard col < row.count, isNumber(row[col]), let y = Double(row[col].filter { "0123456789.-+eE".contains($0) }) else { continue }
319 let x: Series.X
320 if ind > 0, ind - 1 < row.count {
321 let field = row[ind - 1]
322 if plot.timeInd, let m = field.firstMatch(of: try! Regex(EmacsBuffer.timestampPattern)), let stamp = Timestamp.parse(String(field[m.range])) {
323 let p = stamp.start
324 x = .date(calendar.date(from: DateComponents(year: p.year, month: p.month, day: p.day, hour: p.hour ?? 0, minute: p.minute ?? 0)) ?? Date())
325 } else if plot.textInd || o.with == "histograms" {
326 x = .label(field)
327 } else {
328 x = .number(stringToNumber(field))
329 }
330 } else {
331 x = .number(Double(r + 1))
332 }
333 points.append((x, y))
334 }
335 out.append(Series(label: label, points: points))
336 }
337 return out
338 }
339
340 /// The 3d and grid plots' matrix: rows of numbers, without the ind column, and the
341 /// ind column's values for the rows.
342 public static func matrix(_ plot: Plot) -> (values: [[Double]], rowLabels: [String]) {
343 let rows = plot.rows.compactMap { $0 }
344 if plot.options.type == "3d" { return (rows.map { $0.map(stringToNumber) }, []) }
345 let ind = plot.options.ind - 1
346 var deps = plot.options.deps.map { $0.map { $0 - 1 } } ?? Array(0..<(rows.first?.count ?? 0))
347 deps.removeAll { $0 == ind }
348 let values = rows.map { row in row.indices.filter(deps.contains).map { stringToNumber(row[$0]) } }
349 return (values, ind >= 0 ? rows.map { ind < $0.count ? $0[ind] : "" } : [])
350 }
351}
Sources/OrgCore/Keymap/PresetDoom.swift +1 −1
@@ -5,7 +5,7 @@ extension KeymapPreset {
5 let translations: [String: String] = ["<left>": "h", "<right>": "l", "<up>": "k", "<down>": "j"] 5 let translations: [String: String] = ["<left>": "h", "<right>": "l", "<up>": "k", "<down>": "j"]
6 var out = "" 6 var out = ""
7 func bind(_ keys: String, _ command: String, when: String?, mode: String) { 7 func bind(_ keys: String, _ command: String, when: String?, mode: String) {
8 out += "[[bind]]\nkeys = \"\(keys.replacingOccurrences(of: "\\", with: "\\\\"))\"\ncommand = \"\(command)\"\n" 8 out += "[[bind]]\nkeys = \"\(keys.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\""))\"\ncommand = \"\(command)\"\n"
9 if let when { out += "when = \"\(when)\"\n" } 9 if let when { out += "when = \"\(when)\"\n" }
10 out += "mode = \"\(mode)\"\n" 10 out += "mode = \"\(mode)\"\n"
11 } 11 }
Sources/OrgCore/Keymap/PresetEmacs.swift +3
@@ -194,6 +194,9 @@ extension KeymapPreset {
194 keys = "C-c C-x C-l" 194 keys = "C-c C-x C-l"
195 command = "org.latex-preview" 195 command = "org.latex-preview"
196 [[bind]] 196 [[bind]]
197 keys = "C-c \\" g"
198 command = "app.plot"
199 [[bind]]
197 keys = "C-c C-x C-c" 200 keys = "C-c C-x C-c"
198 command = "org.columns" 201 command = "org.columns"
199 [[bind]] 202 [[bind]]
Sources/OrgEditorAppKit/EditorCommands.swift +1
@@ -107,6 +107,7 @@ public enum EditorCommands {
107 EditorCommand(id: "app.clock.report", title: "Clock Report", action: .app), 107 EditorCommand(id: "app.clock.report", title: "Clock Report", action: .app),
108 EditorCommand(id: "app.table-import", title: "Import Table from File…", action: .app), 108 EditorCommand(id: "app.table-import", title: "Import Table from File…", action: .app),
109 EditorCommand(id: "app.table-export", title: "Export Table to File…", action: .app), 109 EditorCommand(id: "app.table-export", title: "Export Table to File…", action: .app),
110 EditorCommand(id: "app.plot", title: "Plot Table", action: .app),
110 EditorCommand(id: "app.export-dialog", title: "Export…", action: .app), 111 EditorCommand(id: "app.export-dialog", title: "Export…", action: .app),
111 EditorCommand(id: "app.sync-conflicts", title: "Resolve Sync Conflicts…", action: .app), 112 EditorCommand(id: "app.sync-conflicts", title: "Resolve Sync Conflicts…", action: .app),
112 EditorCommand(id: "app.revert", title: "Revert to File on Disk", action: .app), 113 EditorCommand(id: "app.revert", title: "Revert to File on Disk", action: .app),
Sources/OrgEditorAppKit/OrgEditor+Images.swift +1 −1
@@ -25,7 +25,7 @@ extension OrgEditor {
25 } 25 }
26 } 26 }
27 27
28 func refreshImages() { 28 public func refreshImages() {
29 keepingTopLine { 29 keepingTopLine {
30 restyleOutsideEditing(0..<utf16Length) 30 restyleOutsideEditing(0..<utf16Length)
31 invalidateAllLayout() 31 invalidateAllLayout()
Sources/Orgstar/ContentView.swift +42
@@ -337,6 +337,10 @@ struct ContentView: View {
337 ExportSheet(source: source, inSubtree: exportSubtreeAvailable, target: exportTarget) { format, destination, open, subtree, bodyOnly in 337 ExportSheet(source: source, inSubtree: exportSubtreeAvailable, target: exportTarget) { format, destination, open, subtree, bodyOnly in
338 export(format, to: destination, open: open, subtree: subtree, bodyOnly: bodyOnly) 338 export(format, to: destination, open: open, subtree: subtree, bodyOnly: bodyOnly)
339 } 339 }
340 case .plot(_, let plot):
341 PlotSheet(content: .chart(plot))
342 case .plotImage(_, let url):
343 PlotSheet(content: .image(url))
340 case .conflict: 344 case .conflict:
341 ConflictSheet(session: session) 345 ConflictSheet(session: session)
342 case .syncCopies: 346 case .syncCopies:
@@ -664,6 +668,42 @@ struct ContentView: View {
664 } 668 }
665 } 669 }
666 670
671 /// `org-plot/gnuplot` for the table at the caret: through gnuplot when it's installed, as
672 /// Emacs runs it, else drawn here; written to `file:` when the options name one, else shown.
673 private func plotTable() {
674 guard let editor = commands.editor, let path = session.path else { return commands.show("No file is open") }
675 let context = editor.context()
676 let plot: TablePlot.Plot
677 do { plot = try TablePlot.plot(context.text, at: context.caret) } catch { return commands.show("\(error)") }
678 let directory = URL(fileURLWithPath: path).deletingLastPathComponent()
679 if let gnuplot = PlotOutput.gnuplot {
680 commands.show("Plotting with gnuplot…")
681 Task {
682 do {
683 let image = try await PlotOutput.runGnuplot(plot, directory: directory, gnuplot: gnuplot)
684 if plot.options.file == nil { panel = .plotImage(UUID(), image) } else { plotWritten(image, editor: editor) }
685 } catch {
686 commands.show("\(error)")
687 }
688 }
689 } else if let url = PlotOutput.file(plot, directory: directory) {
690 do {
691 try PlotOutput.write(plot, to: url)
692 plotWritten(url, editor: editor)
693 } catch {
694 commands.show("\(error)")
695 }
696 } else {
697 panel = .plot(UUID(), plot)
698 }
699 }
700
701 /// The image is where `file:` says; a link to it shows it again.
702 private func plotWritten(_ url: URL, editor: OrgEditor) {
703 commands.show("Plot written to \(url.lastPathComponent)")
704 if editor.showsImages { editor.refreshImages() }
705 }
706
667 /// `org-publish`, `org-publish-all`, `org-publish-current-file` and 707 /// `org-publish`, `org-publish-all`, `org-publish-current-file` and
668 /// `org-publish-current-project`, with the projects in config.toml. 708 /// `org-publish-current-project`, with the projects in config.toml.
669 private func publish(_ id: String) { 709 private func publish(_ id: String) {
@@ -1004,6 +1044,8 @@ struct ContentView: View {
1004 export(String(id.dropFirst("app.export.".count))) 1044 export(String(id.dropFirst("app.export.".count)))
1005 case let id where id.hasPrefix("app.publish"): 1045 case let id where id.hasPrefix("app.publish"):
1006 publish(id) 1046 publish(id)
1047 case "app.plot":
1048 plotTable()
1007 default: 1049 default:
1008 if let editor = commands.editor { editor.run(id) } else { commands.show("No file is open") } 1050 if let editor = commands.editor { editor.run(id) } else { commands.show("No file is open") }
1009 } 1051 }
Sources/Orgstar/Panels.swift +4 −1
@@ -7,10 +7,13 @@ enum Panel: Identifiable {
7 case conflict(UUID) 7 case conflict(UUID)
8 case syncCopies(UUID) 8 case syncCopies(UUID)
9 case recovery(UUID) 9 case recovery(UUID)
10 /// A `#+PLOT` table drawn here, or gnuplot's image of it.
11 case plot(UUID, TablePlot.Plot)
12 case plotImage(UUID, URL)
10 13
11 var id: UUID { 14 var id: UUID {
12 switch self { 15 switch self {
13 case .columns(let id, _), .export(let id, _), .conflict(let id), .syncCopies(let id), .recovery(let id): id 16 case .columns(let id, _), .export(let id, _), .conflict(let id), .syncCopies(let id), .recovery(let id), .plot(let id, _), .plotImage(let id, _): id
14 } 17 }
15 } 18 }
16} 19}
Sources/Orgstar/PlotSheet.swift added +36
@@ -0,0 +1,36 @@
1import AppKit
2import OrgApp
3import OrgCore
4import SwiftUI
5
6/// A plotted table: drawn by Swift Charts, or the image gnuplot made.
7struct PlotSheet: View {
8 enum Content {
9 case chart(TablePlot.Plot)
10 case image(URL)
11 }
12
13 let content: Content
14 @Environment(\.dismiss) private var dismiss
15
16 var body: some View {
17 VStack(spacing: 0) {
18 switch content {
19 case .chart(let plot):
20 PlotChart(plot)
21 case .image(let url):
22 if let image = NSImage(contentsOf: url) {
23 Image(nsImage: image).resizable().scaledToFit().padding()
24 } else {
25 Text("gnuplot made no image").foregroundStyle(.secondary)
26 }
27 }
28 HStack {
29 Spacer()
30 Button("Done") { dismiss() }.keyboardShortcut(.defaultAction)
31 }
32 .padding(10)
33 }
34 .frame(minWidth: 640, minHeight: 520)
35 }
36}
Sources/OrgstarMobile/EditorScreen.swift +41 −1
@@ -51,6 +51,7 @@ struct EditorScreen: View {
51 case refile(String) 51 case refile(String)
52 case block(BlockEdit) 52 case block(BlockEdit)
53 case columns(ColumnView.View) 53 case columns(ColumnView.View)
54 case plot(TablePlot.Plot)
54 55
55 var id: String { 56 var id: String {
56 switch self { 57 switch self {
@@ -61,6 +62,7 @@ struct EditorScreen: View {
61 case .recovery: "recovery" 62 case .recovery: "recovery"
62 case .block(let edit): "block \(edit.range)" 63 case .block(let edit): "block \(edit.range)"
63 case .columns: "columns" 64 case .columns: "columns"
65 case .plot: "plot"
64 } 66 }
65 } 67 }
66 } 68 }
@@ -92,6 +94,7 @@ struct EditorScreen: View {
92 Button("Import Table from File…", systemImage: "square.and.arrow.down") { importingTable = true } 94 Button("Import Table from File…", systemImage: "square.and.arrow.down") { importingTable = true }
93 Button("Export Table as CSV…", systemImage: "square.and.arrow.up") { exportTable(csv: true) } 95 Button("Export Table as CSV…", systemImage: "square.and.arrow.up") { exportTable(csv: true) }
94 Button("Export Table as TSV…", systemImage: "square.and.arrow.up") { exportTable(csv: false) } 96 Button("Export Table as TSV…", systemImage: "square.and.arrow.up") { exportTable(csv: false) }
97 Button("Plot Table", systemImage: "chart.xyaxis.line") { plotTable() }
95 } 98 }
96 Toggle(isOn: Binding(get: { model.showMarkup }, set: { model.showMarkup = $0 })) { 99 Toggle(isOn: Binding(get: { model.showMarkup }, set: { model.showMarkup = $0 })) {
97 Label("Show Markup", systemImage: "chevron.left.forwardslash.chevron.right") 100 Label("Show Markup", systemImage: "chevron.left.forwardslash.chevron.right")
@@ -157,6 +160,8 @@ struct EditorScreen: View {
157 } 160 }
158 case .columns(let view): 161 case .columns(let view):
159 ColumnViewScreen(view: view, session: session, path: path) { offset in editor?.reveal(offset) } 162 ColumnViewScreen(view: view, session: session, path: path) { offset in editor?.reveal(offset) }
163 case .plot(let plot):
164 PlotScreen(plot: plot)
160 } 165 }
161 } 166 }
162 .fileImporter(isPresented: $importingTable, allowedContentTypes: [.commaSeparatedText, .tabSeparatedText, .plainText]) { result in 167 .fileImporter(isPresented: $importingTable, allowedContentTypes: [.commaSeparatedText, .tabSeparatedText, .plainText]) { result in
@@ -260,6 +265,8 @@ struct EditorScreen: View {
260 importingTable = true 265 importingTable = true
261 } else if id == "app.table-export" { 266 } else if id == "app.table-export" {
262 exportTable(csv: true) 267 exportTable(csv: true)
268 } else if id == "app.plot" {
269 plotTable()
263 } else if id == "app.toggle-markup" { 270 } else if id == "app.toggle-markup" {
264 model.showMarkup.toggle() 271 model.showMarkup.toggle()
265 } else if MobileEditor.linkCommands.contains(id) { 272 } else if MobileEditor.linkCommands.contains(id) {
@@ -290,6 +297,25 @@ extension EditorScreen {
290 _ = editor.perform(ImportTable(contents: contents)) 297 _ = editor.perform(ImportTable(contents: contents))
291 } 298 }
292 299
300 /// `org-plot/gnuplot`, drawn by Swift Charts: written to `file:` when the options name
301 /// one, else shown.
302 private func plotTable() {
303 guard let editor else { return }
304 let context = editor.editContext()
305 do {
306 let plot = try TablePlot.plot(context.text, at: context.caret)
307 if let url = PlotOutput.file(plot, directory: URL(fileURLWithPath: path).deletingLastPathComponent()) {
308 try PlotOutput.write(plot, to: url)
309 message = "Plot written to \(url.lastPathComponent)"
310 if editor.showsImages { editor.restyleAll() }
311 } else {
312 sheet = .plot(plot)
313 }
314 } catch {
315 message = "\(error)"
316 }
317 }
318
293 /// `org-table-export` of the table at the caret, as CSV or TSV. 319 /// `org-table-export` of the table at the caret, as CSV or TSV.
294 private func exportTable(csv: Bool) { 320 private func exportTable(csv: Bool) {
295 guard let editor else { return } 321 guard let editor else { return }
@@ -592,7 +618,7 @@ struct CommandPalette: View {
592 ("org.toggle-inline-images", "Show or Hide Inline Images"), ("org.latex-preview", "Show or Hide LaTeX Previews"), ("editor.toggle-truncate-lines", "Truncate or Wrap Long Lines"), 618 ("org.toggle-inline-images", "Show or Hide Inline Images"), ("org.latex-preview", "Show or Hide LaTeX Previews"), ("editor.toggle-truncate-lines", "Truncate or Wrap Long Lines"),
593 ("org.table.toggle-column-width", "Shrink or Expand Table Column"), ("org.table.shrink", "Shrink Table Columns with Widths"), 619 ("org.table.toggle-column-width", "Shrink or Expand Table Column"), ("org.table.shrink", "Shrink Table Columns with Widths"),
594 ("org.table.expand", "Expand Table Columns"), 620 ("org.table.expand", "Expand Table Columns"),
595 ("app.table-import", "Import Table from File…"), ("app.table-export", "Export Table to File…"), 621 ("app.table-import", "Import Table from File…"), ("app.table-export", "Export Table to File…"), ("app.plot", "Plot Table"),
596 ] 622 ]
597 623
598 /// The commands that apply at the caret and their keys, worked out once when the palette 624 /// The commands that apply at the caret and their keys, worked out once when the palette
@@ -650,4 +676,18 @@ struct TableFile: FileDocument {
650 FileWrapper(regularFileWithContents: Data(text.utf8)) 676 FileWrapper(regularFileWithContents: Data(text.utf8))
651 } 677 }
652} 678}
679/// A plotted table, as the Mac's plot sheet shows it.
680struct PlotScreen: View {
681 let plot: TablePlot.Plot
682 @Environment(\.dismiss) private var dismiss
683
684 var body: some View {
685 NavigationStack {
686 PlotChart(plot)
687 .navigationTitle("Plot")
688 .navigationBarTitleDisplayMode(.inline)
689 .toolbar { ToolbarItem(placement: .confirmationAction) { Button("Done") { dismiss() } } }
690 }
691 }
692}
653#endif 693#endif
Sources/OrgstarMobile/MobileEditor.swift +1 −1
@@ -302,7 +302,7 @@ final class MobileEditor: NSObject, DocumentBuffer {
302 case "app.clock.in", "app.clock.out", "app.clock.cancel", "app.clock.goto", "app.clock.in-recent", "app.clock.in-last", 302 case "app.clock.in", "app.clock.out", "app.clock.cancel", "app.clock.goto", "app.clock.in-recent", "app.clock.in-last",
303 "app.clock.goto-recent", "app.clock.default", "app.clock.resolve", "app.toggle-markup": return onAppCommand != nil 303 "app.clock.goto-recent", "app.clock.default", "app.clock.resolve", "app.toggle-markup": return onAppCommand != nil
304 case "app.refile.goto", "app.table-import": return onAppCommand != nil 304 case "app.refile.goto", "app.table-import": return onAppCommand != nil
305 case "app.table-export": return onAppCommand != nil && ImportTable.exportText(context.text, at: context.caret, path: "") != nil 305 case "app.table-export", "app.plot": return onAppCommand != nil && ImportTable.exportText(context.text, at: context.caret, path: "") != nil
306 case "app.refile", "app.refile.copy": return onAppCommand != nil && Presentation.heading(containing: context.caret, in: context.tree) != nil 306 case "app.refile", "app.refile.copy": return onAppCommand != nil && Presentation.heading(containing: context.caret, in: context.tree) != nil
307 case _ where Self.linkCommands.contains(id): return onAppCommand != nil 307 case _ where Self.linkCommands.contains(id): return onAppCommand != nil
308 case "org.link.open": return OpenLinkAtPoint().applies(in: context) 308 case "org.link.open": return OpenLinkAtPoint().applies(in: context)
Tests/OrgAppTests/PlotChartTests.swift added +38
@@ -0,0 +1,38 @@
1import Foundation
2import OrgCore
3@testable import OrgApp
4import Testing
5
6@MainActor
7struct PlotChartTests {
8 @Test func writesImagesAndPDF() throws {
9 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-plotchart-\(UUID().uuidString)")
10 defer { try? FileManager.default.removeItem(at: folder) }
11 let texts = [
12 "#+PLOT: title:\"Lines\" ind:1 file:\"a.png\"\n| x | a | b |\n|---+---+---|\n| 1 | 2 | 3 |\n| 2 | 4 | 1 |\n| 3 | 3 | 5 |\n",
13 "#+PLOT: ind:1 with:histograms file:\"b.jpg\"\n| name | n |\n|------+---|\n| a | 3 |\n| b | 5 |\n",
14 "#+PLOT: type:grid ind:1 file:\"c.pdf\"\n| r | a | b |\n|---+---+---|\n| x | 1 | 2 |\n| y | 3 | 4 |\n",
15 "#+PLOT: type:3d file:\"d.png\"\n| 1 | 2 | 3 |\n| 2 | 4 | 6 |\n| 3 | 6 | 9 |\n",
16 ]
17 for text in texts {
18 let plot = try TablePlot.plot(text, at: (text as NSString).range(of: "|").location)
19 let url = try #require(PlotOutput.file(plot, directory: folder))
20 try PlotOutput.write(plot, to: url)
21 let size = (try FileManager.default.attributesOfItem(atPath: url.path)[.size] as? Int) ?? 0
22 #expect(size > 1000, "\(url.lastPathComponent) is \(size) bytes")
23 if let copy = ProcessInfo.processInfo.environment["ORGSTAR_PLOT_DUMP"] {
24 try? FileManager.default.removeItem(atPath: copy + "/" + url.lastPathComponent)
25 try FileManager.default.copyItem(atPath: url.path, toPath: copy + "/" + url.lastPathComponent)
26 }
27 }
28 let svg = try TablePlot.plot("#+PLOT: file:\"e.svg\"\n| 1 | 2 |\n", at: 25)
29 #expect(throws: PlotOutput.Failure.self) { try PlotOutput.write(svg, to: PlotOutput.file(svg, directory: folder)!) }
30 }
31
32 @Test func interpolatesTheMatrix() {
33 let m: [[Double]] = [[1, 2], [3, 4]]
34 #expect(PlotChart.Surface.interpolate(m, 1, 1) == 1)
35 #expect(PlotChart.Surface.interpolate(m, 2, 2) == 4)
36 #expect(PlotChart.Surface.interpolate(m, 1.5, 1.5) == 2.5)
37 }
38}
Tests/OrgCoreTests/TablePlotTests.swift added +126
@@ -0,0 +1,126 @@
1import Foundation
2import Testing
3@testable import OrgCore
4
5struct TablePlotTests {
6 static let cases: [String] = [
7 """
8 #+PLOT: title:"Sales" ind:1 deps:(2 3) type:2d with:lines set:"grid" set:"xrange [0:10]" line:"set key left"
9 | x | a | b | c |
10 |---+---+---+---|
11 | 1 | 2 | 3 | 4 |
12 | 2 | 4 | 5 | 6 |
13 """,
14 """
15 #+PLOT: with:points
16 | 1 | 10 |
17 | 2 | 20 |
18 | 3 | 15 |
19 """,
20 """
21 #+PLOT: ind:1 with:histograms title:"By name"
22 | name | count |
23 |-------+-------|
24 | apple | 3 |
25 | "pear | 5 |
26 """,
27 """
28 #+NAME: series
29 #+PLOT: ind:1 deps:(2) with:linespoints
30 | day | value |
31 |------------------+-------|
32 | <2026-01-05 Mon> | 1.5 |
33 | [2026-01-06 Tue 10:30] | 2 |
34 """,
35 """
36 #+PLOT: type:3d map:t with:lines
37 | 1 | 2 | 3 |
38 | 4 | 5 | 6 |
39 | 7 | 8 | 9 |
40 """,
41 """
42 #+PLOT: type:grid ind:1 title:"Heat"
43 | row | a | b |
44 |-----+---+---|
45 | r1 | 1 | 2 |
46 | r2 | 3 | 4 |
47 """,
48 """
49 #+PLOT: transpose:yes ind:1
50 | x | 1 | 2 | 3 |
51 |---+---+---+---|
52 | y | 4 | 5 | 6 |
53 """,
54 """
55 #+PLOT: labels:("first" "second") ind:1 file:"/tmp/orgstar-plot-test.png"
56 #+PLOT: set:"title 'Upper'"
57 | 1 | 2 |
58 | 3 | 4 |
59 """,
60 ]
61
62 static func lisp(_ s: String) -> String {
63 "\"" + s.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\"") + "\""
64 }
65
66 /// The script and the data file `org-plot/gnuplot` writes, gnuplot itself left out.
67 static func emacs(_ text: String, data: String) throws -> (script: String, data: String) {
68 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-plot-\(UUID().uuidString)")
69 try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
70 defer { try? FileManager.default.removeItem(at: folder) }
71 let output = folder.appendingPathComponent("script.txt").path
72 let form = """
73 (progn
74 (require 'org) (require 'org-plot)
75 (defun gnuplot-mode ())
76 (defun gnuplot-send-buffer-to-gnuplot ())
77 (provide 'gnuplot)
78 (let ((captured nil))
79 (cl-letf (((symbol-function 'gnuplot-send-buffer-to-gnuplot) (lambda () (setq captured (buffer-string))))
80 ((symbol-function 'org-babel-temp-stable-file) (lambda (&rest _) \(lisp(data)))))
81 (with-temp-buffer
82 (insert \(lisp(text)))
83 (org-mode)
84 (goto-char (point-min))
85 (re-search-forward "^|")
86 (org-plot/gnuplot)))
87 (with-temp-file \(lisp(output)) (insert captured))))
88 """
89 let log = try EmacsOracle.run(["-Q", "--batch", "--eval", form], environment: ["TZ": "UTC"])
90 guard let script = try? String(contentsOfFile: output, encoding: .utf8) else { throw EmacsOracle.EvaluateError(log: log) }
91 return (script, (try? String(contentsOfFile: data, encoding: .utf8)) ?? "")
92 }
93
94 @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil), arguments: cases.indices)
95 func scriptsAndDataMatchEmacs(index: Int) throws {
96 let text = Self.cases[index]
97 let dataFile = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-plot-data-\(UUID().uuidString)").path
98 defer { try? FileManager.default.removeItem(atPath: dataFile) }
99 let expected = try Self.emacs(text, data: dataFile)
100 let offset = (text as NSString).range(of: "|").location
101 let plot = try TablePlot.plot(text, at: offset)
102 var utc = Calendar(identifier: .gregorian)
103 utc.timeZone = TimeZone(identifier: "UTC")!
104 let (data, labels): (String, [(Int, String)]) = plot.options.type == "grid" ? TablePlot.gridData(plot) : (TablePlot.data(plot, calendar: utc), [])
105 let script = TablePlot.script(plot, dataFile: dataFile, output: plot.options.file, yLabels: labels)
106 #expect(script == expected.script, "case \(index)\nours:\n\(script)\nemacs:\n\(expected.script)")
107 #expect(data == expected.data, "case \(index)\nours:\n\(data.debugDescription)\nemacs:\n\(expected.data.debugDescription)")
108 }
109
110 @Test func seriesAndMatrices() throws {
111 let plot = try TablePlot.plot(Self.cases[0], at: 100)
112 let series = TablePlot.series(plot)
113 #expect(series.map(\.label) == ["a", "b"])
114 #expect(series[0].points.map(\.y) == [2, 4] && series[0].points.first?.x == .number(1))
115 let text = try TablePlot.plot(Self.cases[2], at: 60)
116 #expect(text.textInd && TablePlot.series(text)[0].points.first?.x == .label("apple"))
117 let dated = try TablePlot.plot(Self.cases[3], at: 80)
118 #expect(dated.timeInd)
119 if case .date = TablePlot.series(dated)[0].points[0].x {} else { Issue.record("not a date") }
120 let grid = try TablePlot.plot(Self.cases[5], at: 60)
121 let m = TablePlot.matrix(grid)
122 #expect(m.values == [[1, 2], [3, 4]] && m.rowLabels == ["r1", "r2"])
123 #expect(throws: TablePlot.Failure.self) { try TablePlot.plot("#+PLOT: type:radar\n| 1 |\n", at: 0) }
124 #expect(throws: TablePlot.Failure.self) { try TablePlot.plot("no table\n", at: 0) }
125 }
126}
docs/manual/guide/03-keys.org +1
@@ -1023,6 +1023,7 @@ No preset binds these. Run them from the palette or a menu, or bind them in =key
1023| Resolve Sync Conflicts… (=app.sync-conflicts=) | Shows the file's sync conflict copies to resolve them. | 1023| Resolve Sync Conflicts… (=app.sync-conflicts=) | Shows the file's sync conflict copies to resolve them. |
1024| Import Table from File… (=app.table-import=) | Asks for a CSV, TSV or space-separated file and inserts it as a table (=org-table-import=). | 1024| Import Table from File… (=app.table-import=) | Asks for a CSV, TSV or space-separated file and inserts it as a table (=org-table-import=). |
1025| Export Table to File… (=app.table-export=) | Writes the table at point to a CSV or TSV file (=org-table-export=). | 1025| Export Table to File… (=app.table-export=) | Writes the table at point to a CSV or TSV file (=org-table-export=). |
1026| Plot Table (=app.plot=) | Plots the table at point as its =#+PLOT:= lines say (=org-plot/gnuplot=, =C-c " g= in the Emacs and Doom presets). |
1026| Show or Hide Outline (=app.toggle-outline=) | Shows or hides the outline pane. View ▸ Show or Hide Outline, =⌥⌘O=. | 1027| Show or Hide Outline (=app.toggle-outline=) | Shows or hides the outline pane. View ▸ Show or Hide Outline, =⌥⌘O=. |
1027| Show or Hide Backlinks (=app.toggle-backlinks=) | Shows or hides the backlinks pane. View ▸ Show or Hide Backlinks. | 1028| Show or Hide Backlinks (=app.toggle-backlinks=) | Shows or hides the backlinks pane. View ▸ Show or Hide Backlinks. |
1028| Show or Hide Columns and Clock (=app.toggle-inspector=) | Shows or hides the columns and clock inspector. View ▸ Show or Hide Columns and Clock, =⌥⌘I=. | 1029| Show or Hide Columns and Clock (=app.toggle-inspector=) | Shows or hides the columns and clock inspector. View ▸ Show or Hide Columns and Clock, =⌥⌘I=. |
docs/manual/guide/10-tables.org +44 −4
@@ -565,13 +565,53 @@ export writes them as a code block. See [[file:12-export.org][Export]].
565 565
566* Plotting 566* Plotting
567 567
568=#+PLOT:= lines are recognized and completed as keywords, but orgstar doesn't draw 568Plot Table (=org-plot/gnuplot=, =C-c " g= in the Emacs and Doom presets, and in the
569plots (=org-plot/gnuplot= is not available). 569command palette; More › Table on iOS) draws the table at the caret, or the first table
570after it, as the =#+PLOT:= lines above it say:
571
572#+BEGIN_SRC org
573#+PLOT: title:"Sales" ind:1 deps:(2 3) type:2d with:linespoints file:"sales.png"
574| month | north | south |
575|-------+-------+-------|
576| 1 | 20 | 12 |
577| 2 | 25 | 18 |
578#+END_SRC
579
580| Option | Meaning |
581|------------+-----------------------------------------------------------------------------|
582| =type= | =2d= (the default), =3d= or =grid= |
583| =ind= | The column of x values, counting from 1; 0 (the default) plots against row numbers |
584| =deps= | The columns to plot, as a list such as =(2 3)=; all but =ind= by default |
585| =with= | =lines= (the default), =points=, =linespoints=, =impulses=, =boxes=, =histograms=, =steps=, =fsteps= |
586| =title= | The plot's title |
587| =file= | Where the image goes, relative to the Org file's folder; without it the plot shows in a sheet |
588| =labels= | Names for the columns, as a list; a header row above a rule names them otherwise |
589| =map= | With =t=, a =3d= plot is seen from above |
590| =ymin=, =ymax=, =xmin=, =xmax= | The axes' ranges; =min= and =max= are =ymin= and =ymax= |
591| =ticks= | How many marks the y axis has |
592| =transpose= | With =yes=, rows become columns |
593| =set=, =line=, =script=, =timefmt= | gnuplot commands, a line of gnuplot, a gnuplot script file and the time format, for gnuplot |
594
595Options are read as Org reads them, quirks included: an option's name also matches inside
596a longer word (=timeind:t= sets =ind=), an unquoted value ends at a =.=, =,= or =;=, =set:=
597options before the last =line:= are dropped, and each =set:= and =line:= that's kept comes
598twice, as Org reads the options twice. An ind column of timestamps is plotted as dates, and one of text as labels.
599
600On the Mac, when gnuplot is installed (orgstar looks on the same =PATH= as code blocks), the
601table goes to gnuplot as Emacs sends it: the same data file and script, so every option and
602gnuplot's own terminals and styles apply. A plot without =file:= is drawn to an image and shown
603in a sheet. Without gnuplot, and on iOS, orgstar draws the plot itself with Swift Charts: =2d=
604as lines, points or bars by =with:=, =grid= as a heat map, =3d= as a surface (a wireframe in a
605file). =file:= then takes =.png=, =.jpg= or =.pdf=, 640 by 480 points as gnuplot's default; the
606gnuplot-only options are ignored. If inline images are showing, a link to the file shows the
607new plot.
608
609=type:radar= needs gnuplot; orgstar reports it.
570 610
571* On iOS 611* On iOS
572 612
573The iOS app evaluates formulas natively with the same engine. Tables that need Emacs 613The iOS app evaluates formulas natively with the same engine. Tables that need Emacs
574are not recalculated there; the app reports =This table needs Emacs, which runs on the 614are not recalculated there; the app reports =This table needs Emacs, which runs on the
575Mac= with the reason. Table import and export are Mac only. Narrow columns work in the 615Mac= with the reason. Import and export are under More › Table, with Plot Table.
576editor, as described under /Narrow columns/. See 616Narrow columns work in the editor, as described under /Narrow columns/. See
577[[file:14-ios.org][iOS]]. 617[[file:14-ios.org][iOS]].