Tests/OrgCoreTests/TableFormulaTests.swift

374 lines · 30331 bytes

  1import Foundation
  2import Testing
  3@testable import OrgCore
  4
  5struct TableFormulaTests {
  6    static let tables = [
  7        "| a | b |\n|---+---|\n| 1 |   |\n| 2 |   |\n| 3 |   |\n#+TBLFM: $2=$1*2\n",
  8        "| x | y | sum |\n|---+---+-----|\n| 1 | 2 |     |\n| 3.5 | 4 | |\n|---+---+-----|\n|   |   |     |\n#+TBLFM: $3=$1+$2::@>$1=vsum(@I..@II)::@>$2=vmean(@2$2..@3$2)\n",
  9        "| qty | price | total | share |\n|-----+-------+-------+-------|\n| 3 | 19.99 | | |\n| 1 | 5 | | |\n| 12 | 0.5 | | |\n|-----+-------+-------+-------|\n| | | | |\n#+TBLFM: $3=$1*$2;%.2f::$4=$3/@>$3;f3::@>$3=vsum(@I..@II)\n",
 10        "| n | sq | cube | root |\n|---+----+------+------|\n| 1 | | | |\n| 2 | | | |\n| 10 | | | |\n#+TBLFM: $2=$1^2::$3=$1^3::$4=sqrt($1)\n",
 11        "| a | b |\n| 1 | |\n| 2 | |\n| 7 | |\n#+TBLFM: $2=$1/2\n",
 12        "| a | prev | next |\n|---+------+------|\n| 1 | | |\n| 2 | | |\n| 3 | | |\n#+TBLFM: $2=@-1$1::$3=@+1$1\n",
 13        "| a | b | c |\n|---+---+---|\n| 1 | 2 | |\n| 4 | 5 | |\n#+TBLFM: $3=$-1*$-2::@2$3=100\n",
 14        "| r | v |\n|---+---|\n| 1 | |\n| 2 | |\n| 3 | |\n#+TBLFM: @2$2..@4$2=$1*10\n",
 15        "| r | v |\n|---+---|\n| 1 | |\n| 2 | |\n#+TBLFM: $>=@#*$#\n",
 16        "| a | b | c |\n|---+---+---|\n| 1 |   | |\n|   | 2 | |\n#+TBLFM: $3=$1+$2\n",
 17        "| a | b |\n|---+---|\n| 5 | |\n| 6 | |\n#+TBLFM: $2=$1*3\n#+TBLFM: $2=$1+100\n",
 18        "| a | b |\n|---+---|\n| 1 |\n| 2 | |\n#+TBLFM: $3=$1*$1\n",
 19        "| a | b | c |\n|---+---+---|\n| 1 | 2 | |\n| 3 | 4 | |\n#+TBLFM: $3=vsum($1..$2)::@2=7\n",
 20        "| a | b |\n|---+---|\n| 1.25 | |\n| 0.1 | |\n| 1e3 | |\n| -2 | |\n#+TBLFM: $2=$1/7\n",
 21        "| deg | sin | cos |\n|-----+-----+-----|\n| 0 | | |\n| 30 | | |\n| 45 | | |\n| 90 | | |\n#+TBLFM: $2=sin($1)::$3=cos($1);%.3f\n",
 22        "  | a | b |\n  |---+---|\n  | 2 |   |\n  | 3 |   |\n  #+TBLFM: $2=$1^0.5;n4\n",
 23        "| a | b |\n|---+---|\n| x | |\n| 2 | |\n#+TBLFM: $2=$1*2\n",
 24        "| a | b |\n|---+---|\n| 1 | |\n|---+---|\n| 2 | |\n| 3 | |\n#+TBLFM: $2=@I$1+@II$1+@-I$1\n",
 25        "| a | b | c |\n|---+---+---|\n| 1 | 2 | |\n#+TBLFM: $3=($1+$2)*2/3-1::$1=$1\n",
 26        "| a |\n|---|\n| 1 |\n| 2 |\n|---|\n| |\n#+TBLFM: @>$1=vmax(@I..@II)-vmin(@I..@II)+vcount(@I..@II)+vmedian(@I..@II)\n",
 27        "#+CONSTANTS: c=10 k=2.5\n| a | b |\n|---+---|\n| 1 | |\n| 2 | |\n#+TBLFM: $2=$1*$c+$k\n",
 28        "* Rates\n:PROPERTIES:\n:Rate:     3\n:END:\n| h | pay |\n|---+-----|\n| 2 | |\n#+TBLFM: $2=$1*$PROP_Rate\n",
 29        // Errors partway through: the fields written before them stay.
 30        "| a | b | c |\n|---+---+---|\n| 1 | | |\n| 22 | | |\n| 3 | | |\n#+TBLFM: $2=$1*2::$3=@-2$1\n",
 31        "| a | b | c |\n|---+---+---|\n| 1 | | |\n| 22 | | |\n| 3 | | |\n#+TBLFM: $2=$1*2::@3$3=@-5$1::@2$3=7\n",
 32        "| a | b |\n|---+---|\n| 1 |  |\n| 2 |  |\n#+TBLFM: $2=$1::@I$1=3\n",
 33        "| a | b |\n|---+---|\n| 1 |  |\n| 2 |  |\n#+TBLFM: $2=$1*3::@2$2=1::@2$1..@3$2=5\n",
 34        // A field formula's field of one space still gets the column formula first.
 35        "| a | b |\n|---+---|\n| # | |\n| 2 | |\n#+TBLFM: $2=@0$1+1::@3$2=$2*10\n",
 36        "| a | b |\n|---+---|\n| # |  |\n| 2 |  |\n| 3 ||\n#+TBLFM: $2=@0$1+1::@3$2=$2*10::@4$2=$2*10\n",
 37    ]
 38
 39    /// Lisp formulas, names, parameters, marked rows, remote tables, durations, dates and
 40    /// the rest that once needed Emacs: all run natively.
 41    static let native = [
 42        "| a | b | c | d | mean | ratio | gmean | more |\n|---+---+---+---+------+-------+-------+------|\n| 1:30 | 2 | 3 | 4.5 | | | | |\n| 2:4 | 5 | 1 | 2 | | | | |\n#+TBLFM: $5=vmean($2..$3,$4)::$6=$2/$3;p15::$7=vgmean($2..$4);f3::$8=$4% + $1 2 + roundu($4) + hypot($2,$3)\n",
 43        "| a | b |\n|---+---|\n| hello | |\n| x \"q\" | |\n|  | |\n#+TBLFM: $2='(concat $1 \"!\")\n",
 44        "| a | b |\n|---+---|\n| 1 | |\n| 2.5 | |\n| x | |\n#+TBLFM: $2='(* 2 $1);N\n",
 45        "| a | b | c |\n|---+---+---|\n| 1 | 2 | |\n| 3 | 4 | |\n#+TBLFM: $3='(+ $1 $2);L\n",
 46        "| a |\n|---|\n| 1 |\n| 2 |\n|---|\n| |\n#+TBLFM: @>$1='(apply '+ '(@I..@II));N\n",
 47        "| a | b |\n|---+---|\n| 1 | |\n#+TBLFM: $2='(car 1)\n",
 48        "| a | b | c | d | e | f |\n|---+---+---+---+---+---|\n| 1 | | | | | |\n#+TBLFM: $2='(list 1 2)::$3='(list \"a\" \"b\")::$4='(cons \"a\" \"b\");%.2f::$5='(list \"a b\" (list \"c\"))::$6='(list)\n",
 49        "| a | b | c |\n|---+---+---|\n| 3.14159 | | |\n| 2 | | |\n#+TBLFM: $2='(format \"%05.1f\" $1);N::$3='(+ $1 1);N%.2f\n",
 50        "| a | b |\n|---+---|\n| 5 | |\n| 12 | |\n#+TBLFM: $2='(if (> $1 10) \"big\" \"small\");N\n",
 51        "| ! | qty | price | total |\n|---+-----+-------+-------|\n|   | 2 | 3 | |\n|   | 4 | 0.5 | |\n#+TBLFM: $4=$qty*$price\n",
 52        "|   | x | y |\n|---+---+---|\n| # | 2 |   |\n|   | 3 |   |\n| * | 4 |   |\n| $ | k=10 | |\n#+TBLFM: $3=$2*$k\n",
 53        "|   | a  | b  |\n|---+----+----|\n|   | 1  | 2  |\n| ^ | aa | bb |\n| _ |    | cc |\n|   |    |    |\n#+TBLFM: $cc=$aa+$bb::$2=7\n",
 54        "|   | a  | b  |\n|---+----+----|\n|   | 1  | 2  |\n| _ |    | dd |\n#+TBLFM: $dd=1\n",
 55        "| start | end | sum | diff | hours |\n|-------+-----+-----+------+-------|\n| 1:30 | 0:45 | | | |\n| 10:00:30 | 2:15:10 | | | |\n|-------+-----+-----+------+-------|\n| | | | | |\n#+TBLFM: $3=$1+$2;T::$4=$1-$2;U::$5=$1*2;t::@>$1=vsum(@I..@II);T\n",
 56        "| d1 | d2 | days | later |\n|----+----+------+-------|\n| <2026-10-05 Mon> | <2026-10-12 Mon> | | |\n| [2026-01-31 Sat] | [2026-03-01 Sun] | | |\n| <2026-10-05 Mon 08:30> | <2026-10-05 Mon 10:00> | | |\n#+TBLFM: $3=$2-$1::$4=$1+7\n",
 57        "| d | until |\n|---+-------|\n| <2026-10-05 Mon> | |\n#+TBLFM: $2=<2026-12-25 Fri>-$1\n",
 58        "| a | b | c | d |\n|---+---+---+---|\n| 1 |   | | |\n| 2 | 3 | | |\n#+TBLFM: $3=$1+$2;E::$4=vcount($1..$2);E\n",
 59        "| a | b | c |\n|---+---+---|\n| 5 | 3 | |\n| 2 | 9 | |\n#+TBLFM: $3=if($1>$2, $1, $2)\n",
 60        "| a | b | c |\n|---+---+---|\n| 7 | 3 | |\n| -7 | 2 | |\n#+TBLFM: $3=$1%$2+$1\\$2*100\n",
 61        "#+NAME: rates\n| item | rate |\n|------+------|\n| a    | 2    |\n| b    | 3    |\n\n| x | y | z | w |\n|---+---+---+---|\n| 4 | | | |\n#+TBLFM: $2=$1*remote(rates,@2$2)::$3=remote(rates, B3)::$4=vsum(remote(rates,@2$2..@>$2))\n",
 62        "#+NAME: prices\n| fruit | price |\n|-------+-------|\n| apple | 1.5 |\n| pear | 2 |\n\n| item | cost |\n|------+------|\n| pear | |\n| plum | |\n#+TBLFM: $2='(org-lookup-first $1 '(remote(prices,@2$1..@>$1)) '(remote(prices,@2$2..@>$2)))\n",
 63        "#+CONSTANTS: c=3\n| a | b | c |\n|---+---+---|\n| 2 | | |\n#+TBLFM: $2='(* $c $1);N::$3=$1*$c\n",
 64        "|   | a | b |\n|---+---+---|\n|   | 2 | |\n|   | 3 | |\n| $ | %=%.2f | |\n#+TBLFM: $3=$2/3;\n",
 65        "| a | b |\n|---+---|\n| 4 | |\n| 9 | |\n#+TBLFM: $2=vsdev(@I$1..@II$1)+fact(3)\n",
 66        "| a | b |\n|---+---|\n| 1 |   |\n| 2 |   |\n#+TBLFM: @-1$2=5\n",
 67        "| a | b | f |\n|---+---+---|\n| 1 | 3 |  |\n| 7 | 2 |  |\n| -7 | 2 |  |\n| 6 | 3 |  |\n| 1 | 0.5 |  |\n| 4 | 6 |  |\n#+TBLFM: $3=$1/$2;F\n",
 68        "| a |\n|---|\n|  |\n|  |\n|  |\n|  |\n|  |\n|  |\n|  |\n|  |\n|  |\n#+TBLFM: @2$1=1/3+1/6;F::@3$1=(1/3)^2;F::@4$1=vsum([1/2,1/3]);F::@5$1=1/3*3;F::@6$1=sqrt(1/4);F::@7$1=vmean([1,2]);F::@8$1=2^-2;F::@9$1=abs(-1/3)+max(1/3,1/4);F::@10$1=round(7/2)+floor(7/2);F\n",
 69        "| 10 | 20 | |\n| 1 | 2 | |\n| 3 | 4 | |\n#+TBLFM: $3=@0$1+@0$2*10\n",
 70        "#+NAME: t1\n| 5 | 6 |\n| 1 | 2 |\n\n#+NAME: t2\n| 7 | 8 |\n\n| name | val | sum |\n|------+-----+-----|\n| t1 | | |\n| t2 | | |\n#+TBLFM: $2=remote($1,@1$1)::$3=vsum(remote(t1,$1..$2))+vsum($1..$2)\n",
 71    ]
 72
 73    /// Timestamps in fields and formulas, with and without the duration flags, and Calc's
 74    /// date functions.
 75    static let dates = [
 76        "| d1 | d2 | diff | T | t | U | N |\n|----+----+------+---+---+---+---|\n| <2026-01-01 Thu> | <2026-01-03 Sat> | | | | | |\n| <2026-01-01 Thu 10:00> | <2026-01-03 Sat 12:30> | | | | | |\n| [2026-01-01 Thu] | <2026-01-03 Sat 00:00> | | | | | |\n#+TBLFM: $3=$2-$1::$4=$2-$1;T::$5=$2-$1;t::$6=$2-$1;U::$7=$2-$1;N\n",
 77        "| d | later | T | left |\n|---+-------+---+------|\n| <2026-10-05 Mon 00:00> | | | |\n| <2026-10-05 Mon 23:30> | | | |\n| [2026-10-05 Mon 12:00] | | | |\n#+TBLFM: $2=$1+0.5::$3=$1+1;T::$4=<2026-12-25 Fri>-$1\n",
 78        "| d | y | m | wd | yd | h | next | start | week | year |\n|---+---+---+----+----+---+------+-------+------+------|\n| <2026-10-05 Mon> | | | | | | | | | |\n| <2026-01-31 Sat 09:15> | | | | | | | | | |\n| [2024-02-29 Thu] | | | | | | | | | |\n#+TBLFM: $2=year($1)::$3=month($1)::$4=weekday($1)::$5=yearday($1)::$6=hour($1)+minute($1)::$7=incmonth($1,1)::$8=newmonth($1)::$9=newweek($1,1)::$10=incyear($1)\n",
 79        "| d | due | days | jd | n | back |\n|---+-----+------+----+---+------|\n| <2026-10-09 Fri> | | | | | |\n| <2026-10-10 Sat 08:00> | | | | | |\n#+TBLFM: $2=badd($1,3)::$3=bsub(badd($1,10),$1)::$4=julian(floor($1))::$5=date($1)::$6=date(2026,1,1)+floor($1-date(2026,1,1))\n",
 80        "| d | abs | next |\n|---+-----+------|\n| <2026-01-01 Thu> | | |\n| <0070-01-01 Thu> | | |\n| [0010-01-01 Fri] | | |\n#+TBLFM: $2=abs(-$1)::$3=$1+1\n",
 81        "| d |\n|---|\n| <2026-10-05 Mon> |\n| <2026-10-07 Wed 06:00> |\n|---|\n| |\n| |\n| |\n#+TBLFM: @4$1=vmean(@I..@II)::@5$1=vmin(@I..@II)::@6$1=vmax(@I..@II)\n",
 82    ]
 83
 84    /// Results that aren't numbers under `N` and the duration flags: `#ERROR`, or for a
 85    /// duration an error.
 86    static let numericResults = [
 87        "| a | b | c | d | e | f | g |\n|---+---+---+---+---+---+---|\n| <2026-01-01 Thu> | | | | | | |\n#+TBLFM: $2=<2026-01-01 Thu>+$1;N::$3=<2026-01-01 Thu>;E::$4=<2026-01-01 Thu>;EN::$5=<2026-01-01 Thu>;ET::$6=nan;N::$7=1/3;NF\n",
 88        "| a | b |\n|---+---|\n| 1 | |\n#+TBLFM: $2=$1/3;TF\n",
 89        "| a | b |\n|---+---|\n| 1 | |\n#+TBLFM: $2=nan;T\n",
 90        "| a | b |\n|---+---|\n| <2026-01-01 Thu> | |\n#+TBLFM: $2=<2026-12-25 Fri>-$1;U\n",
 91    ]
 92
 93    /// Text and blank fields, which Calc reads as variables and zero, and the `S` flag.
 94    static let symbolic = [
 95        "| item | cost |\n|------+------|\n| a | 5 |\n| b | N/A |\n| c | 3 |\n|------+------|\n| total | |\n| mean | |\n#+TBLFM: @>>$2=vsum(@I..@II)::@>$2=vmean(@I..@II)\n",
 96        "| a | b | ratio | twice |\n|---+---+-------+-------|\n| 6 | 0 | | |\n| 6 | | | |\n| 4.5 | 2 | | |\n| TBD | 4 | | |\n| 5 kg | 2 | | |\n#+TBLFM: $3=$1/$2::$4=2*$1+$2\n",
 97        "| r | area | half |\n|---+------+------|\n| 3 | | |\n| x | | |\n#+TBLFM: $2=$1^2*pi::$3=$2/2;S\n",
 98        "| a | b | c | d |\n|---+---+---+---|\n| 1 | | n/a | |\n| 2 | 3 | | |\n#+TBLFM: $4=vsum($1..$3)::@2$2=$1 + inf;S\n",
 99        "| a | b | c |\n|---+---+---|\n| x | 1 | |\n| | 2 | |\n#+TBLFM: $3=$1*$2;E\n",
100        // Functions of text fields.
101        "| name | q1 | q2 | q3 | best | worst |\n|------+----+----+----+------+-------|\n| ann | 5 | 7 | 6 | | |\n| bob | 4 | absent | 8 | | |\n| cy | | 2.5 | 1 | | |\n#+TBLFM: $5=vmax($2..$4)::$6=vmin($2..$4)\n",
102        "| item | qty | status | flag |\n|------+-----+--------+------|\n| a | 12 | | |\n| b | n/a | | |\n| c | 3 | | |\n| d | TBD | | |\n#+TBLFM: $3=if($2 > 10, 1, 0)::$4=$2 >= 3 && $2 != 12\n",
103        "| x | abs | root | low | mod |\n|---+-----+------+-----+-----|\n| -4 | | | | |\n| TBD | | | | |\n| 9 | | | | |\n#+TBLFM: $2=abs($1)::$3=sqrt(abs($1))::$4=min($1, 5)::$5=$1 % 4\n",
104        "| a | b | same | e | ln |\n|---+---+------+---+----|\n| N/A | N/A | | | |\n| 1 | 2 | | | |\n| x | y | | | |\n#+TBLFM: $3=$1 == $2::$4=exp($1)::$5=ln($2)\n",
105        "| a | not | below |\n|---+-----+-------|\n| TBD | | |\n| 2 | | |\n#+TBLFM: $2=!$1 + 1::$3=!$1 < 1\n",
106        "| a | b | c |\n|---+---+---|\n| TBD | -3 | |\n#+TBLFM: $3=if($1 > 0, -$2, 0)\n",
107        "| a | b | c | d | max | min |\n|---+---+---+---+-----+-----|\n|   |   | TBD | 1 | | |\n#+TBLFM: $5=vmax($1..$2, $3..$4)::$6=vmin($1..$2, $3..$4)\n",
108        // Calc rejects a number with two points.
109        "| a | b |\n|---+---|\n| 21.11.2026 | |\n| 192.168.1.1 | |\n| 1.5 | |\n#+TBLFM: $2=$1+1\n",
110        "| a | b |\n|---+---|\n| 21.11.2026 | |\n#+TBLFM: $2=$1+1;T\n",
111        "| a | b |\n|---+---|\n| 1:00 | |\n#+TBLFM: $2=$1+x;T\n",
112        "| a | b |\n|---+---|\n| 1:00 | |\n#+TBLFM: $2=$1+x*y;T\n",
113    ]
114
115    /// A range of one field with a space is a vector without commas, which Calc splits at the
116    /// space; a power or quotient left symbolic under a duration flag has Calc's explanation.
117    @Test func refusesWhatCalcReadsOrExplainsDifferently() {
118        for text in [
119            "| a | b | c |\n|---+---+---|\n| 5 kg | | |\n#+TBLFM: $3=vsum($1..$2)\n",
120            "| a | b | c |\n|---+---+---|\n| 1 2 | | |\n#+TBLFM: $3=vsum($1..$2)\n",
121            "| a | b |\n|---+---|\n| N A | |\n| | |\n#+TBLFM: @2$2=vmean(@2$1..@3$1)\n",
122            "| a | b |\n|---+---|\n| 1:00 | |\n#+TBLFM: $2=$1+x^2/x;T\n",
123            "| a | b |\n|---+---|\n| 1:00 | |\n#+TBLFM: $2=$1+x*x;T\n",
124            "| a | b |\n|---+---|\n| 1:00 | |\n#+TBLFM: $2=$1+x x;T\n",
125        ] {
126            let caret = (text as NSString).range(of: "#+TBLFM").location + 3
127            let failure = Self.recalculate(TableRecalculate(all: true), text, caret: caret).failure ?? ""
128            #expect(failure.hasPrefix("external:"), "\(failure) in\n\(text)")
129        }
130    }
131
132    @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
133    func textAndBlankFieldsMatchEmacsNatively() throws {
134        try compare(Self.symbolic, fallbacksAllowed: false, headerFallbacksAllowed: false)
135    }
136
137    @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
138    func datesMatchEmacs() throws {
139        try compare(Self.dates + Self.numericResults, fallbacksAllowed: false)
140    }
141
142    @Test func remoteFindsTablesByIDInOtherFiles() {
143        let other = "* Elsewhere\n:PROPERTIES:\n:ID: far\n:END:\n| v |\n|---|\n| 7 |\n"
144        RemoteTables.fileWithID = { $0 == "far" ? other : nil }
145        defer { RemoteTables.fileWithID = nil }
146        let text = "| x | y |\n|---+---|\n| 3 | |\n#+TBLFM: $2=$1*remote(far,@2$1)\n"
147        let result = runCommand(TableRecalculate(all: true), text, caret: (text as NSString).range(of: "#+TBLFM").location + 3)
148        #expect(result.text.contains("| 3 | 21 |"), "\(result)")
149        // As Emacs does in a file buffer (`org-id-find` needs one): the entry's first table.
150        let local = "* Rates\n:PROPERTIES:\n:ID: rates-id\n:END:\n| item | rate |\n|------+------|\n| a    | 2    |\n* Use\n| x | y |\n|---+---|\n| 4 | |\n#+TBLFM: $2=$1*remote(rates-id,@2$2)\n"
151        #expect(runCommand(TableRecalculate(all: true), local, caret: (local as NSString).range(of: "#+TBLFM").location + 3).text.contains("| 4 | 8 |"))
152        let missing = runCommand(TableRecalculate(all: true), text.replacingOccurrences(of: "far", with: "nowhere"), caret: 2)
153        #expect(missing.failure == "Can't find remote table \"nowhere\"")
154    }
155
156    static func carets(_ text: String) -> [Int] {
157        let ns = text as NSString
158        var result: [Int] = []
159        var location = 0
160        while location < ns.length {
161            let line = ns.lineRange(for: NSRange(location: location, length: 0))
162            let content = ns.substring(with: line)
163            if let bar = content.firstIndex(of: "|"), !content.contains("|-") {
164                // Inside the first field of the row.
165                result.append(line.location + content.distance(from: content.startIndex, to: bar) + 2)
166            }
167            if content.uppercased().contains("#+TBLFM") { result.append(line.location + 3) }
168            location = NSMaxRange(line)
169        }
170        return result
171    }
172
173    @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
174    func matchesEmacs() throws {
175        try compare(Self.tables, fallbacksAllowed: true)
176    }
177
178    @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
179    func extendedFormulasMatchEmacsNatively() throws {
180        try compare(Self.native, fallbacksAllowed: false)
181    }
182
183    /// Lisp formulas with regexps, math, sequences, loops and dates: all run natively.
184    static let lisp = [
185        "| name | starred | words |\n|------+---------+-------|\n| apple pie | | |\n| kiwi | | |\n#+TBLFM: $2='(replace-regexp-in-string \"[aeiou]\" \"*\" $1)::$3='(length (split-string $1))\n",
186        "| code | number |\n|------+--------|\n| ab-12 | |\n| none | |\n#+TBLFM: $2='(if (string-match \"[0-9]+\" $1) (match-string 0 $1) \"-\")\n",
187        "| n | root | square | sum |\n|---+------+--------+-----|\n| 4 | | | |\n| 10 | | | |\n#+TBLFM: $2='(sqrt $1);N::$3='(expt $1 2);N::$4='(cl-loop for i from 1 to $1 sum i);N\n",
188        "| day | weekday | since |\n|-----+---------+-------|\n| <2026-11-20 Fri> | | |\n| [2026-03-01 Sun] | | |\n#+TBLFM: $2='(format-time-string \"%A\" (org-time-string-to-time $1))::$3='(- (org-time-string-to-absolute $1) (org-time-string-to-absolute \"<2026-01-01 Thu>\"))\n",
189        "| tags | sorted |\n|------+--------|\n| c,a,b | |\n#+TBLFM: $2='(string-join (sort (split-string $1 \",\") #'string<) \"+\")\n",
190        "| kind | label |\n|------+-------|\n| 1 | |\n| 2 | |\n| 7 | |\n#+TBLFM: $2='(pcase $1 (1 \"one\") (2 \"two\") (_ \"many\"));N\n",
191    ]
192
193    @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
194    func lispFormulasMatchEmacsNatively() throws {
195        try compare(Self.lisp, fallbacksAllowed: false)
196    }
197
198    /// With `headerFallbacksAllowed`, a formula Calc would leave symbolic over a header's
199    /// text may go to Emacs even when other fallbacks aren't allowed.
200    func compare(_ tables: [String], fallbacksAllowed: Bool, headerFallbacksAllowed: Bool = true) throws {
201        var cases: [EmacsOracle.Case] = []
202        var ours: [(text: String, caret: Int, failure: String?)] = []
203        for text in tables {
204            for caret in Self.carets(text) {
205                let onTblfm = (text as NSString).substring(with: (text as NSString).lineRange(for: NSRange(location: caret, length: 0))).uppercased().contains("#+TBLFM")
206                let commands: [(any OrgCommand, String)] = onTblfm
207                    ? [(TableRecalculate(all: true), "(org-ctrl-c-ctrl-c)")]
208                    : [(TableRecalculate(all: true), "(org-table-recalculate t)"), (TableRecalculate(all: false), "(org-table-recalculate nil)")]
209                for (command, form) in commands {
210                    cases.append(EmacsOracle.Case(text: text, point: EmacsOracle.point(caret, in: text), form: form))
211                    ours.append(Self.recalculate(command, text, caret: caret))
212                }
213            }
214        }
215        let emacs = try EmacsOracle.run(cases)
216        var fallbacks = 0
217        for (i, (mine, theirs)) in zip(ours, emacs).enumerated() {
218            if let failure = mine.failure, failure.hasPrefix("external:") {
219                fallbacks += 1
220                let header = failure.contains("symbolic") || failure.contains("of a formula")
221                #expect(fallbacksAllowed || (headerFallbacksAllowed && header), "\(failure) in\n\(cases[i].text)")
222                continue
223            }
224            let expected = (theirs.text, EmacsOracle.offset(theirs.point, in: theirs.text), theirs.error.isEmpty ? nil : theirs.error)
225            #expect(mine.text == expected.0 && mine.caret == expected.1 && mine.failure == expected.2,
226                    "\(cases[i].form) at \(cases[i].point) in\n\(cases[i].text)\nours:\n\(mine.text)@\(mine.caret) \(mine.failure ?? "")\nemacs:\n\(theirs.text)@\(expected.1) \(theirs.error)")
227        }
228        #expect(fallbacks < ours.count / 2, "\(fallbacks) fallbacks")
229    }
230
231    /// Two formulas, then one only Emacs can do: in row order, as Emacs applies them.
232    static let unsupported = "| a | b | c | d |\n|---+---+---+---|\n| 1 | | | |\n| 2 | | | |\n#+TBLFM: $2=$1*2::$3=$1+1::$4='(shell-command-to-string $1)\n"
233
234    @Test func lispConsIsAnError() {
235        let text = "| a | b | c | d | e |\n|---+---+---+---+---|\n| 1 | | | | |\n#+TBLFM: $2='(list 1 2)::$3='(cons \"a\" \"b\");N%.2f::$4='(list 'quote '(\"a\" \"b\"))::$5='(list)\n"
236        let caret = (text as NSString).range(of: "#+TBLFM").location
237        let result = Self.recalculate(TableRecalculate(all: true), text, caret: caret)
238        #expect(result.failure == nil)
239        #expect(result.text.hasPrefix("| a | b      | c      | d      | e   |\n|---+--------+--------+--------+-----|\n| 1 | #ERROR | #ERROR | #ERROR | nil |\n"))
240        let duration = "| a | b |\n|---+---|\n| 1 | |\n#+TBLFM: $2='(list 1 2);T\n"
241        let context = EditContext(revision: 0, text: duration, tree: OrgParser.parse(duration), selection: [3..<3])
242        guard case .external(.emacsTable(_, _, _, let reason, _, _, _)) = TableRecalculate(all: true).run(in: context) else {
243            Issue.record("not a request")
244            return
245        }
246        #expect(reason == "Lisp formula with a list value and a duration")
247    }
248
249    @Test func keepsFieldsWrittenBeforeAFormulaOnlyEmacsCanDo() {
250        let text = Self.unsupported
251        let caret = (text as NSString).range(of: "#+TBLFM").location + 3
252        let context = EditContext(revision: 0, text: text, tree: OrgParser.parse(text), selection: [caret..<caret])
253        guard case .external(.emacsTable(_, _, _, let reason, let lisp, let formula, let partial?)) = TableRecalculate(all: true).run(in: context) else {
254            Issue.record("not a request")
255            return
256        }
257        #expect(reason == "Lisp function shell-command-to-string")
258        #expect(lisp)
259        #expect(formula == "$4")
260        let result = partial.edits.reduce(text) { $1.apply(to: $0) }
261        #expect(result == "| a | b | c | d |\n|---+---+---+---|\n| 1 | 2 | 2 | |\n| 2 | | | |\n#+TBLFM: $2=$1*2::$3=$1+1::$4='(shell-command-to-string $1)\n")
262        // Point stays on the #+TBLFM line, after the two digits written.
263        #expect(partial.selection == [(caret + 4)..<(caret + 4)])
264    }
265
266    /// The fields kept before a formula only Emacs can do are what Emacs leaves when that
267    /// formula fails instead.
268    @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
269    func keptFieldsMatchEmacsAfterAnError() throws {
270        let failing = "@-9$1"
271        let lisp = "'(shell-command-to-string $1)"
272        let tables = [
273            Self.unsupported,
274            "| a | b | c |\n|---+---+---|\n| 1 | | |\n| 2 | | |\n| 3 | | |\n#+TBLFM: $2=$1*3::@3$3=\(lisp)::@2$3=7::@4$3=8\n",
275            "| a | b |\n|---+---|\n| # | |\n| 2 | |\n#+TBLFM: $2=@0$1+1::@3$2=\(lisp)\n",
276            "|   | a | b | c |\n|---+---+---+---|\n| # | 1 |   |   |\n#+TBLFM: $3=$2*2::$4=\(lisp)\n",
277        ]
278        var cases: [EmacsOracle.Case] = []
279        var ours: [(text: String, caret: Int)] = []
280        for text in tables {
281            let emacsText = text.replacingOccurrences(of: lisp, with: failing)
282            for caret in Self.carets(text) {
283                let onTblfm = (text as NSString).substring(with: (text as NSString).lineRange(for: NSRange(location: caret, length: 0))).contains("#+TBLFM")
284                let commands: [(any OrgCommand, String)] = onTblfm
285                    ? [(TableRecalculate(all: true), "(org-ctrl-c-ctrl-c)")]
286                    : [(TableRecalculate(all: true), "(org-table-recalculate t)"), (TableRecalculate(all: false), "(org-table-recalculate nil)"), (TableIterate(), "(org-table-iterate)"),
287                       (TableCommand(.nextField), "(org-table-next-field)"), (TableCommand(.previousField), "(org-table-previous-field)"), (TableCommand(.nextRow), "(org-table-next-row)")]
288                for (command, form) in commands {
289                    let context = EditContext(revision: 0, text: text, tree: OrgParser.parse(text), selection: [caret..<caret])
290                    let step = command.run(in: context)
291                    // Rows at point without the Lisp formula, and header rows Calc reads as symbols.
292                    guard case .external(.emacsTable(_, _, _, let reason, _, _, let partial?)) = step, reason.hasPrefix("Lisp") else { continue }
293                    cases.append(EmacsOracle.Case(text: emacsText, point: EmacsOracle.point(caret, in: emacsText), form: form))
294                    let new = partial.edits.reduce(text) { $1.apply(to: $0) }
295                    ours.append((new, partial.selection?.first?.lowerBound ?? caret))
296                }
297            }
298        }
299        #expect(cases.count >= 8)
300        #expect(cases.filter { ["(org-table-next-field)", "(org-table-previous-field)", "(org-table-next-row)"].contains($0.form) }.count == 3)
301        for (i, (theirs, mine)) in zip(try EmacsOracle.run(cases), ours).enumerated() {
302            #expect(theirs.error.contains("leads outside table"), "\(theirs.error)")
303            let text = theirs.text.replacingOccurrences(of: failing, with: lisp)
304            let point = EmacsOracle.offset(theirs.point, in: theirs.text)
305            let shifted = point > (theirs.text as NSString).range(of: failing).location ? point + (text as NSString).length - (theirs.text as NSString).length : point
306            #expect(mine.text == text && mine.caret == shifted, "\(cases[i].form) at \(cases[i].point)\nours:\n\(mine.text)@\(mine.caret)\nemacs:\n\(text)@\(shifted)")
307        }
308    }
309
310    /// TAB, S-TAB and RET in a row marked `#`, and recalculations with point inside a field,
311    /// when a formula fails: the fields written before it stay and point goes to the field's start.
312    @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
313    func errorsKeepFieldsAndMovePointAsEmacs() throws {
314        let marked = "|   | a | b | c |\n|---+---+---+---|\n| # | 1 |   |   |\n#+TBLFM: $3=$2*2::$4=@-9$2\n"
315        let early = "| a | b |\n|---+---|\n| 1 |x|\n| 2 |y |\n#+TBLFM: $2=$1*2::@2$2=7::@3$2=8::@2$1=@-9$1\n"
316        let fine = "|   | a | b |\n|---+---+---|\n| # | 1 |   |\n|   | 2 |   |\n#+TBLFM: $3=$2*2\n"
317        func after(_ needle: String, in text: String) -> Int { NSMaxRange((text as NSString).range(of: needle)) }
318        let runs: [(text: String, caret: Int, command: any OrgCommand, form: String)] = [
319            (marked, after("| # | 1", in: marked), TableCommand(.nextField), "(org-table-next-field)"),
320            (marked, after("| # | 1", in: marked), TableCommand(.previousField), "(org-table-previous-field)"),
321            (marked, after("| # | 1", in: marked), TableCommand(.nextRow), "(org-table-next-row)"),
322            (marked, after("| # | 1 |  ", in: marked), TableCommand(.nextField), "(org-table-next-field)"),
323            (early, after("| 2", in: early), TableRecalculate(all: true), "(org-table-recalculate t)"),
324            (early, after("| 2 |y", in: early), TableRecalculate(all: true), "(org-table-recalculate t)"),
325            (early, after("| 1 |", in: early), TableRecalculate(all: false), "(org-table-recalculate nil)"),
326            (fine, after("| # | 1", in: fine), TableCommand(.nextField), "(org-table-next-field)"),
327            (fine, after("| # | 1", in: fine), TableCommand(.previousField), "(org-table-previous-field)"),
328            (fine, after("| # | 1", in: fine), TableCommand(.nextRow), "(org-table-next-row)"),
329        ]
330        let cases = runs.map { EmacsOracle.Case(text: $0.text, point: EmacsOracle.point($0.caret, in: $0.text), form: $0.form) }
331        for (i, theirs) in try EmacsOracle.run(cases).enumerated() {
332            let mine = Self.recalculate(runs[i].command, runs[i].text, caret: runs[i].caret)
333            let expected = (theirs.text, EmacsOracle.offset(theirs.point, in: theirs.text), theirs.error.isEmpty ? nil : theirs.error)
334            #expect(mine.text == expected.0 && mine.caret == expected.1 && mine.failure == expected.2,
335                    "\(runs[i].form) at \(runs[i].caret) in\n\(runs[i].text)\nours:\n\(mine.text)@\(mine.caret) \(mine.failure ?? "")\nemacs:\n\(theirs.text)@\(expected.1) \(theirs.error)")
336        }
337    }
338
339    /// `runCommand`, with the message of an error that left fields written as the failure.
340    static func recalculate(_ command: any OrgCommand, _ text: String, caret: Int) -> (text: String, caret: Int, failure: String?) {
341        let result = runCommand(command, text, caret: caret)
342        let context = EditContext(revision: 0, text: text, tree: OrgParser.parse(text), selection: [caret..<caret])
343        guard case .commit(let commit) = command.run(in: context), case .message(let message) = commit.effects.last else { return result }
344        return (result.text, result.caret, message)
345    }
346
347    /// `ORGSTAR_ORACLE_CORPUS=<folder>`: C-c C-c on every `#+TBLFM` line below the folder.
348    @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_ORACLE_CORPUS"] != nil))
349    func corpusMatchesEmacs() throws {
350        let root = URL(fileURLWithPath: ProcessInfo.processInfo.environment["ORGSTAR_ORACLE_CORPUS"]!)
351        let files = FileManager.default.enumerator(at: root, includingPropertiesForKeys: nil)!
352            .compactMap { $0 as? URL }.filter { $0.pathExtension == "org" }.sorted { $0.path < $1.path }
353        var cases: [EmacsOracle.Case] = []
354        var ours: [(text: String, caret: Int, failure: String?)] = []
355        for file in files {
356            guard let text = try? String(contentsOf: file, encoding: .utf8), text.uppercased().contains("#+TBLFM") else { continue }
357            let ns = text as NSString
358            var location = 0
359            while location < ns.length {
360                let line = ns.lineRange(for: NSRange(location: location, length: 0))
361                if ns.substring(with: line).trimmingCharacters(in: .whitespaces).uppercased().hasPrefix("#+TBLFM") {
362                    cases.append(EmacsOracle.Case(text: text, point: EmacsOracle.point(line.location, in: text), form: "(org-ctrl-c-ctrl-c)"))
363                    ours.append(runCommand(TableRecalculate(all: true), text, caret: line.location))
364                }
365                location = NSMaxRange(line)
366            }
367        }
368        let emacs = try EmacsOracle.run(cases)
369        for (mine, theirs) in zip(ours, emacs) where !(mine.failure ?? "").hasPrefix("external:") {
370            #expect(mine.text == theirs.text, "\(mine.failure ?? "")")
371        }
372        print("TBLFM lines: \(cases.count), native: \(ours.filter { !($0.failure ?? "").hasPrefix("external:") }.count)")
373    }
374}