Tests/OrgCoreTests/TableTests.swift
128 lines · 7487 bytes
8 symbols in this file
1import Foundation
2import Testing
3@testable import OrgCore
4
5struct TableTests {
6 @Test func aligns() {
7 let result = runCommand(TableCommand(.align), "|a|bb|\n|ccc|1|\n", caret: 1).text
8 #expect(result == "| a | bb |\n| ccc | 1 |\n")
9 }
10
11 static let variants = [
12 "|a|bb|\n|ccc|1|\n",
13 "| Name | Qty |\n|-\n| apple | 3 |\n| pear | 12 |\n",
14 " | x | y |\n |---+---|\n | 1 | 2 |\n",
15 "| [[https://example.com][link]] | *bold* | =code= |\n| a | b | c |\n",
16 "| \\\\alpha | a_{bc} | x^2 |\n| 1 | 2 | 3 |\n",
17 "| <r> | <c5> |\n| a | b |\n",
18 "| 1 | 2 |\n| 3 | 4 |\n#+TBLFM: $2=$1*2::@2$1=7\n",
19 "text\n| a |\n| b |\nmore\n",
20 "| ü | 漢字 |\n| x | y |\n",
21 "| a | b\n| c |\n",
22 "|-+-|\n",
23 ]
24
25 static let commands: [(command: any OrgCommand, form: String, headingLineOnly: Bool)] = [
26 (TableCommand(.align), "(org-table-align)", false),
27 (TableCommand(.nextField), "(org-table-next-field)", false),
28 (TableCommand(.previousField), "(org-table-previous-field)", false),
29 (TableCommand(.nextRow), "(org-table-next-row)", false),
30 (TableCommand(.moveRowUp), "(org-table-move-row-up)", false),
31 (TableCommand(.moveRowDown), "(org-table-move-row-down)", false),
32 (TableCommand(.moveColumnLeft), "(org-table-move-column-left)", false),
33 (TableCommand(.moveColumnRight), "(org-table-move-column-right)", false),
34 (TableCommand(.insertColumn), "(org-table-insert-column)", false),
35 (TableCommand(.deleteColumn), "(org-table-delete-column)", false),
36 (TableCommand(.killRow), "(org-table-kill-row)", false),
37 (TableCommand(.insertRowAbove), "(org-table-insert-row)", false),
38 (TableCommand(.insertHline), "(org-table-insert-hline)", false),
39 ]
40
41 static func tableCarets(_ text: String) -> [Int] {
42 EmacsOracle.positions(text).filter { offset in
43 let ns = text as NSString
44 let line = ns.lineRange(for: NSRange(location: min(offset, max(0, ns.length - 1)), length: 0))
45 return offset < ns.length && ns.substring(with: line).trimmingCharacters(in: .whitespaces).hasPrefix("|")
46 }
47 }
48
49 @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
50 func tableCommandsMatchEmacs() throws {
51 let inputs = Self.variants.map { ($0, Self.tableCarets($0)) }
52 try compareWithEmacs(inputs, Self.commands)
53 try compareWithEmacs(inputs, Self.commands, options: doomOptions)
54 }
55
56 /// TAB realigns only after an edit (`org-table-may-need-update`), which here changes the width
57 /// of the field left behind. The last row is out of line, so a realign shows. Emacs starts
58 /// as if just aligned, makes the edit, then TABs; we TAB in the same text after the same edit.
59 @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
60 func nextFieldRealignsOnlyAfterAWidthChange() throws {
61 let table = "| a | b |\n|------+----|\n| cc | dd |\n| eeeeeeee | f |\n"
62 let dd = (table as NSString).range(of: "dd").upperBound
63 func edit(_ range: Range<Int>, _ replacement: String) -> String {
64 (table as NSString).replacingCharacters(in: NSRange(range), with: replacement)
65 }
66 let cases: [(label: String, form: String, caret: Int, text: String, after: Int)] = [
67 ("no edit", "", 3, table, 3),
68 ("typed into spare space", "(let ((last-command-event ?x)) (org-self-insert-command 1))", 3, edit(3..<3, "x"), 4),
69 ("typed past the column's width", "(insert \"xxxxxxxxxx\")", 3, edit(3..<3, "xxxxxxxxxx"), 13),
70 ("deleted with spare space left", "(org-delete-backward-char 1)", 3, edit(2..<3, ""), 2),
71 ("deleted from a full field", "(org-delete-backward-char 1)", dd, edit(dd - 1..<dd, ""), dd - 1),
72 ]
73 let emacs = try EmacsOracle.run(cases.map {
74 EmacsOracle.Case(text: table, point: EmacsOracle.point($0.caret, in: table), form: "(progn (setq org-table-may-need-update nil) \($0.form) (org-table-next-field))")
75 })
76 for (c, theirs) in zip(cases, emacs) {
77 let ours = runCommand(TableCommand(.nextField), c.text, caret: c.after)
78 let caret = EmacsOracle.offset(theirs.point, in: theirs.text)
79 #expect(ours.text == theirs.text && ours.caret == caret, "\(c.label): ours \(ours.text.debugDescription)@\(ours.caret) emacs \(theirs.text.debugDescription)@\(caret)")
80 }
81 }
82
83 @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
84 func createTableMatchesEmacs() throws {
85 for (text, caret) in [("", 0), ("x\n", 1), (" \n", 2)] {
86 for size in ["3x2", "1x1", "2x3"] {
87 let emacs = try EmacsOracle.run([EmacsOracle.Case(text: text, point: caret + 1, form: "(org-table-create \"\(size)\")")])[0]
88 let ours = runCommand(CreateTable(), text, caret: caret, answers: ["size": size])
89 #expect(ours.text == emacs.text && ours.caret == EmacsOracle.offset(emacs.point, in: emacs.text), "\(size) in \(text.debugDescription): ours \(ours.text.debugDescription)@\(ours.caret) emacs \(emacs.text.debugDescription)@\(EmacsOracle.offset(emacs.point, in: emacs.text))")
90 }
91 }
92 }
93
94 /// Real tables: `ORGSTAR_ORACLE_CORPUS=<folder>` aligns and TABs in the first cell of up to
95 /// eight table rows per file, in up to 60 files.
96 @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_ORACLE_CORPUS"] != nil))
97 func tablesMatchEmacsOnACorpus() throws {
98 let root = URL(fileURLWithPath: ProcessInfo.processInfo.environment["ORGSTAR_ORACLE_CORPUS"]!)
99 let files = FileManager.default.enumerator(at: root, includingPropertiesForKeys: nil)!
100 .compactMap { $0 as? URL }.filter { $0.pathExtension == "org" }.sorted { $0.path < $1.path }
101 var samples: [(String, [Int])] = []
102 for file in files where samples.count < 60 {
103 guard let text = try? String(contentsOf: file, encoding: .utf8), text.utf16.count <= 30_000, !text.contains("\r") else { continue }
104 let ns = text as NSString
105 var carets: [Int] = []
106 var location = 0
107 var inBlock = false
108 while location < ns.length, carets.count < 8 {
109 let line = ns.lineRange(for: NSRange(location: location, length: 0))
110 let content = ns.substring(with: line)
111 let trimmed = content.trimmingCharacters(in: .whitespaces).lowercased()
112 if trimmed.hasPrefix("#+begin_") { inBlock = true }
113 if trimmed.hasPrefix("#+end_") { inBlock = false }
114 if !inBlock, trimmed.hasPrefix("|"), let bar = content.firstIndex(of: "|") {
115 carets.append(line.location + content.distance(from: content.startIndex, to: bar) + 2)
116 }
117 location = NSMaxRange(line)
118 }
119 if !carets.isEmpty { samples.append((text, carets)) }
120 }
121 let commands: [(command: any OrgCommand, form: String, headingLineOnly: Bool)] = [
122 (TableCommand(.align), "(org-table-align)", false),
123 (TableCommand(.nextField), "(org-table-next-field)", false),
124 ]
125 try compareWithEmacs(samples, commands)
126 try compareWithEmacs(samples, commands, options: doomOptions)
127 }
128}