Sources/OrgCore/Compute/PlotSettings.swift

525225e4f44b53a1ea7559b03462473575dfa523
orgstar/Sources/OrgCore/Compute/PlotSettings.swift

112 lines · 5605 bytes

  1import Foundation
  2
  3/// The gnuplot `set` commands a plot drawn without gnuplot follows, and the options it leaves out.
  4extension TablePlot {
  5    public struct Settings: Sendable, Equatable {
  6        public enum Key: Sendable, Equatable {
  7            case off
  8            /// `top`/`bottom` and `left`/`right`, either left to the chart.
  9            case at(vertical: String?, horizontal: String?)
 10        }
 11
 12        public struct Range: Sendable, Equatable {
 13            public var low: Double?
 14            public var high: Double?
 15        }
 16
 17        public var title: String?
 18        public var xlabel: String?
 19        public var ylabel: String?
 20        public var xrange: Range?
 21        public var yrange: Range?
 22        public var logX = false
 23        public var logY = false
 24        public var grid = false
 25        public var key: Key?
 26        public var xtics: Double?
 27        public var ytics: Double?
 28        /// The options not followed, as written in `#+PLOT`: `set:"…"`, `line:"…"`, `script:"…"`.
 29        public var unfollowed: [String] = []
 30    }
 31
 32    /// The `set` commands each kind of chart can follow.
 33    static func followed(_ plot: Plot) -> Set<String> {
 34        switch plot.options.type {
 35        case "2d":
 36            let numericX = plot.options.ind <= 0 || !(plot.timeInd || plot.textInd || plot.options.with == "histograms")
 37            return numericX ? ["title", "xlabel", "ylabel", "xrange", "yrange", "logscale", "grid", "key", "xtics", "ytics"]
 38                : ["title", "xlabel", "ylabel", "yrange", "logscale y", "grid", "key", "ytics"]
 39        case "grid": return ["title", "xlabel", "ylabel", "key"]
 40        case "3d" where plot.options["map"]?.truthy == true: return ["title", "xlabel", "ylabel", "key"]
 41        // The radar script sets its own key, after these.
 42        default: return ["title"]
 43        }
 44    }
 45
 46    /// The script's `title:`, `line:` and `set:` in the order gnuplot reads them, so a later
 47    /// one wins.
 48    public static func settings(_ plot: Plot) -> Settings {
 49        var s = Settings()
 50        let o = plot.options
 51        let follows = followed(plot)
 52        s.title = o.title
 53        var lines: [String] = [], sets: [String] = []
 54        for line in o.lines {
 55            if !(line.hasPrefix("set ") && apply(String(line.dropFirst(4)), to: &s, follows: follows)) { lines.append("line:\"\(line)\"") }
 56        }
 57        for set in o.sets where !apply(set, to: &s, follows: follows) { sets.append("set:\"\(set)\"") }
 58        // Each comes twice, as Org reads the options twice; list them once, as written.
 59        for u in lines.reversed() + sets.reversed() where !s.unfollowed.contains(u) { s.unfollowed.append(u) }
 60        if let script = o["script"] { s.unfollowed.append("script:\"\(script)\"") }
 61        return s
 62    }
 63
 64    static func apply(_ command: String, to s: inout Settings, follows: Set<String>) -> Bool {
 65        let words = command.split(separator: " ", maxSplits: 1).map(String.init)
 66        guard let name = words.first else { return false }
 67        let rest = words.count > 1 ? words[1].trimmingCharacters(in: .whitespaces) : ""
 68        func quoted() -> String? {
 69            guard let m = rest.firstMatch(of: /^(["'])(.*)\1$/) else { return nil }
 70            return String(m.2)
 71        }
 72        func range() -> Settings.Range? {
 73            guard let m = rest.firstMatch(of: /^\[\s*([^:\]]*?)\s*:\s*([^:\]]*?)\s*\]$/) else { return nil }
 74            func bound(_ t: Substring) -> Double?? { t.isEmpty || t == "*" ? .some(nil) : Double(t).map { .some($0) } }
 75            guard let low = bound(m.1), let high = bound(m.2) else { return nil }
 76            return Settings.Range(low: low, high: high)
 77        }
 78        func step() -> Double? { Double(rest).flatMap { $0 > 0 ? $0 : nil } }
 79        switch name {
 80        case "title", "xlabel", "ylabel":
 81            guard follows.contains(name), let text = quoted() else { return false }
 82            if name == "title" { s.title = text } else if name == "xlabel" { s.xlabel = text } else { s.ylabel = text }
 83        case "xrange", "yrange":
 84            guard follows.contains(name), let r = range() else { return false }
 85            if name == "xrange" { s.xrange = r } else { s.yrange = r }
 86        case "logscale":
 87            let axes = rest.isEmpty ? "xy" : rest
 88            guard ["x", "y", "xy", "yx"].contains(axes), follows.contains("logscale") || (axes == "y" && follows.contains("logscale y")) else { return false }
 89            if axes.contains("x") { s.logX = true }
 90            if axes.contains("y") { s.logY = true }
 91        case "grid":
 92            guard follows.contains(name), rest.isEmpty else { return false }
 93            s.grid = true
 94        case "key":
 95            let words = rest.split(separator: " ").map(String.init)
 96            guard follows.contains(name), words.allSatisfy(["off", "top", "bottom", "left", "right"].contains) else { return false }
 97            if words == ["off"] {
 98                s.key = .off
 99            } else {
100                let vertical = words.filter { $0 == "top" || $0 == "bottom" }, horizontal = words.filter { $0 == "left" || $0 == "right" }
101                guard !words.contains("off"), vertical.count <= 1, horizontal.count <= 1 else { return false }
102                s.key = .at(vertical: vertical.first, horizontal: horizontal.first)
103            }
104        case "xtics", "ytics":
105            guard follows.contains(name), let step = step() else { return false }
106            if name == "xtics" { s.xtics = step } else { s.ytics = step }
107        default:
108            return false
109        }
110        return true
111    }
112}
Keyboard shortcuts

Global

⌘K
Command palette & jump
/
Focus search
?
Show this help
g d
Dashboard
g e
Explore repositories
g n
Notifications

Repository & editor

t
Find file in repository
y
Copy immutable SHA permalink
g c
Code tab
g i
Issues tab
g m
Merge requests tab
g b
Builds tab
⌘↵
Submit active form