Gates in the release scripts; TAB realigns only after a width change !466

merged merged by cmc on 2026-11-22 20:16 UTC · krz/orgstar:issue-193-gates-and-table into main

9 files changed, +250 −6

Layout: unified · split

CONTRIBUTING.org +4
@@ -178,6 +178,10 @@ Each release goes out on three channels, in this order, from the same commit:
1781782. =scripts/release-ios.sh=, the iOS app.
1791793. =scripts/release-macos.sh=, the Mac App Store app.
180180
181Each of them runs the performance gates (=ORGSTAR_GATES=1 swift test -c release --filter GateTests=)
182before it builds anything for signing, and stops if one misses. Run releases on a Mac that is
183otherwise idle, since the gates measure time.
184
181185The App Store builds take their version from =MARKETING_VERSION= in =ios/Orgstar.xcodeproj=,
182186which every target shares and appstore-kit requires to be the same across them. Set it to
183187=<version>= before the release.
Sources/OrgCore/Commands/Table.swift +76 −1
@@ -285,12 +285,87 @@ extension EmacsBuffer {
285285 point = min(lineEnd(point), start + 1)
286286 }
287287
288 /// Display columns of the bars of the table line at `start`, and of the `+` in a rule; nil
289 /// unless the line has the form `org-table-align` gives it: a bar at the end, a space on
290 /// each side of every field, and only dashes between the bars of a rule.
291 func tableSeparatorColumns(_ start: Int) -> [Int]? {
292 let line = substring(start, lineEnd(start))
293 guard line.hasSuffix("|") else { return nil }
294 let rule = line.drop { $0 == " " || $0 == "\t" }.hasPrefix("|-")
295 var columns: [Int] = []
296 var column = 0
297 var segment = ""
298 for c in line {
299 if c == "|" || rule && c == "+" {
300 if !columns.isEmpty {
301 if rule {
302 guard !segment.isEmpty, segment.allSatisfy({ $0 == "-" }) else { return nil }
303 } else {
304 guard segment.count >= 3, segment.first == " ", segment.last == " " else { return nil }
305 }
306 }
307 column += cellWidth(segment)
308 columns.append(column)
309 column += 1
310 segment = ""
311 } else {
312 segment.append(c)
313 }
314 }
315 return columns
316 }
317
318 /// Whether the table line at point is aligned and its bars line up with the line above
319 /// (below, on the first line): no field of it changed width since the table was aligned.
320 /// A field at point that lost characters but still ends in two spaces gets its width back
321 /// first, as `org-delete-char` keeps it, leaving `org-table-may-need-update` alone.
322 func tableLineLinesUp() -> Bool {
323 let start = lineStart(point)
324 func isTableLine(_ offset: Int) -> Bool {
325 substring(offset, lineEnd(offset)).drop { $0 == " " || $0 == "\t" }.hasPrefix("|")
326 }
327 let reference: Int
328 if start > 0, isTableLine(lineStart(start - 1)) {
329 reference = lineStart(start - 1)
330 } else if lineEnd(start) < length, isTableLine(lineEnd(start) + 1) {
331 reference = lineEnd(start) + 1
332 } else {
333 return false
334 }
335 guard let mine = tableSeparatorColumns(start), let theirs = tableSeparatorColumns(reference), mine.count == theirs.count else { return false }
336 if mine == theirs { return true }
337 // The field at point lies between bars `column - 1` and `column`.
338 let column = tableCurrentColumn()
339 guard !atTableHline, column > 0, column < mine.count, mine[..<column] == theirs[..<column] else { return false }
340 let shift = mine[column] - theirs[column]
341 guard shift < 0, (column..<mine.count).allSatisfy({ mine[$0] - theirs[$0] == shift }) else { return false }
342 var bar = start
343 var bars = 0
344 while bar < lineEnd(start) {
345 if character(at: bar) == 124 {
346 if bars == column { break }
347 bars += 1
348 }
349 bar += 1
350 }
351 guard character(at: bar - 1) == 32, character(at: bar - 2) == 32 else { return false }
352 saveExcursion {
353 point = bar
354 insert(String(repeating: " ", count: -shift))
355 }
356 return true
357 }
358
288359 /// `org-table-next-field`.
289360 func tableNextField() throws {
361 let unchanged = (unchangedPrefix, unchangedSuffix)
290362 try tableMaybeEvalFormula()
291363 try tableMaybeRecalculateLine()
292364 moveIntoField()
293 tableAlign()
365 // `org-table-may-need-update`: Org realigns only after the buffer changed since the last
366 // alignment. Without that history, a line that still lines up stands for no change; a
367 // formula's result is a change.
368 if unchanged != (unchangedPrefix, unchangedSuffix) || !tableLineLinesUp() { tableAlign() }
294369 let end = tableEnd()
295370 if atTableHline { endOfLine() }
296371 func toNextBar() -> Bool { searchForward("\\|", bound: end, caseInsensitive: false) != nil }
Tests/OrgCoreTests/TableTests.swift +27
@@ -53,6 +53,33 @@ struct TableTests {
5353 try compareWithEmacs(inputs, Self.commands, options: doomOptions)
5454 }
5555
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
5683 @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
5784 func createTableMatchesEmacs() throws {
5885 for (text, caret) in [("", 0), ("x\n", 1), (" \n", 2)] {
Tests/OrgEditorAppKitTests/GateTests.swift +27 −2
@@ -10,9 +10,11 @@ import Testing
1010/// ORGSTAR_GATES=1 swift test -c release --filter GateTests
1111///
1212/// `ORGSTAR_GATE_FILE` adds a real file to the synthetic ones. Memory limits follow the design:
13/// 10x the file size for typical documents, 45x for the synthetic worst cases.
13/// 10x the file size for typical documents, 45x for the synthetic worst cases. The 10 MB and
14/// workspace budgets are what the code did when they were set, plus headroom. The tests run one
15/// at a time so their timings don't overlap.
1416@MainActor
15@Suite(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_GATES"] != nil))
17@Suite(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_GATES"] != nil), .serialized)
1618struct GateTests {
1719 /// About 1 MB of body text under a single top-level heading.
1820 /// Entries with property and LOGBOOK drawers, all folded when the file opens.
@@ -45,6 +47,23 @@ struct GateTests {
4547 return text
4648 }()
4749
50 /// About 10 MB of headings with planning lines and drawers, paragraphs with markup, lists,
51 /// tables, source blocks and footnotes.
52 static let tenMegabytes: String = {
53 var text = ""
54 var n = 0
55 while text.utf8.count < 10_000_000 {
56 text += "* TODO Heading \(n) :tag:\nSCHEDULED: <2026-10-04 Sun>\n:PROPERTIES:\n:ID: \(n)-uuid\n:END:\n"
57 text += "Paragraph \(n) with *bold*, /italic/, =code=, a [[https://example.com/\(n)][link]] and a footnote[fn:\(n)].\n\n"
58 text += "- item \(n)\n - nested [ ] task\n\n"
59 text += "| id | name |\n|----+------|\n| \(n) | row \(n) |\n\n"
60 text += "#+begin_src swift\nlet n = \(n)\n#+end_src\n\n"
61 text += "[fn:\(n)] Footnote \(n).\n\n"
62 n += 1
63 }
64 return text
65 }()
66
4867 struct Result: CustomStringConvertible {
4968 var name: String
5069 var bytes: Int
@@ -112,5 +131,11 @@ struct GateTests {
112131 #expect(result.newlineP95 < .milliseconds(16), "\(name): blank line")
113132 #expect(result.memoryRatio < memoryLimit, "\(name): memory")
114133 }
134 let large = measure("10 MB mixed document", Self.tenMegabytes)
135 print("GATE \(large)")
136 #expect(large.open < .milliseconds(1_500), "10 MB: open")
137 #expect(large.typingP95 < .milliseconds(400), "10 MB: typing")
138 #expect(large.newlineP95 < .milliseconds(400), "10 MB: blank line")
139 #expect(large.memoryRatio < 40, "10 MB: memory")
115140 }
116141}
Tests/OrgEditorAppKitTests/WorkspaceGateTests.swift added +100
@@ -0,0 +1,100 @@
1import Foundation
2import OrgApp
3import OrgCore
4import Testing
5
6/// Gates for a large workspace: the first index build, the agenda refresh and the backlinks of
7/// a file and a heading. In `GateTests` so they run one at a time with the editor gates.
8extension GateTests {
9 /// Writes `count` notes of eight headings each, about 2 kB a note. Every heading has an ID
10 /// and a paragraph; the first `fiveLinks` notes have five links and the rest four. A third of
11 /// the headings are TODOs, and every hundredth note has one scheduled in the week of
12 /// 5 October 2026.
13 static func writeNotes(_ count: Int, fiveLinks: Int, to folder: URL) throws {
14 let week = ["2026-10-05 Mon", "2026-10-06 Tue", "2026-10-07 Wed", "2026-10-08 Thu", "2026-10-09 Fri", "2026-10-10 Sat", "2026-10-11 Sun"]
15 try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
16 for n in 0..<count {
17 let links = [
18 "[[id:\((n + 1) % count)-0][note \((n + 1) % count)]]",
19 "[[file:note-\((n + 2) % count).org::*Heading \((n + 2) % count).1][a heading]]",
20 "[[*Heading \(n).2]]",
21 "[[file:note-\((n + 3) % count).org]]",
22 "[[https://example.com/\(n)][the web]]"
23 ].prefix(n < fiveLinks ? 5 : 4)
24 var text = "#+title: Note \(n)\n\n"
25 for h in 0..<8 {
26 text += "* \(h % 3 == 0 ? "TODO " : "")Heading \(n).\(h) :tag\(h):\n"
27 if h == 0, n % 100 == 0 { text += "SCHEDULED: <\(week[n / 100 % 7])>\n" }
28 text += ":PROPERTIES:\n:ID: \(n)-\(h)\n:END:\n"
29 text += "Paragraph of heading \(h) in note \(n), with *bold*, /italic/ and =code=, about as long as a note someone wrote. It goes on for a second sentence about nothing in particular.\n"
30 if h < links.count { text += "See \(links[h]).\n" }
31 text += "\n"
32 }
33 try Data(text.utf8).write(to: folder.appendingPathComponent("note-\(n).org"))
34 }
35 }
36
37 /// A folder of `count` notes, indexed on disk as the app does, and how long the first build took.
38 static func workspace(_ count: Int, fiveLinks: Int, in scratch: URL) async throws -> (model: WorkspaceModel, build: Duration) {
39 let notes = scratch.appendingPathComponent("notes")
40 try writeNotes(count, fiveLinks: fiveLinks, to: notes)
41 let model = try WorkspaceModel(directory: scratch.appendingPathComponent("data"))
42 let start = ContinuousClock.now
43 try await model.addRoot(notes)
44 return (model, ContinuousClock.now - start)
45 }
46
47 static func scratch() throws -> URL {
48 let url = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-gates-\(UUID().uuidString)")
49 try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true)
50 return url
51 }
52
53 /// One pass of the backlinks pane: the file's backlinks and the heading's.
54 static func backlinks(_ model: WorkspaceModel) throws -> (found: Int, time: Duration) {
55 let path = model.files.first { $0.name == "note-0.org" }!.path
56 var found = 0
57 let time = try ContinuousClock().measure {
58 found += try model.backlinks(to: Backlinks.Target(path: path)).count
59 found += try model.backlinks(to: Backlinks.Target(path: path, title: "Heading 0.1", id: "0-1")).count
60 }
61 return (found, time)
62 }
63
64 /// 10,000 notes, 49,400 links.
65 @Test func workspaceGates() async throws {
66 let scratch = try Self.scratch()
67 defer { try? FileManager.default.removeItem(at: scratch) }
68 let (model, build) = try await Self.workspace(10_000, fiveLinks: 9_400, in: scratch)
69 #expect(model.files.count == 10_000)
70
71 let agenda = AgendaModel(workspace: model)
72 agenda.agendaFiles = []
73 agenda.includeSubfolders = false
74 let now = DateComponents(calendar: .current, year: 2026, month: 10, day: 5, hour: 12).date!
75 let clock = ContinuousClock()
76 let cold = await clock.measure { await agenda.refresh(open: [:], now: now) }
77 let warm = await clock.measure { await agenda.refresh(open: [:], now: now) }
78 let items = agenda.days.reduce(0) { $0 + $1.items.count }
79 #expect(items > 0)
80
81 let (found, backlinks) = try Self.backlinks(model)
82 #expect(found > 0)
83 print("GATE 10,000 notes: index build \(build), agenda refresh cold \(cold) / warm \(warm) (\(items) items), backlinks over 49,400 links \(backlinks)")
84 #expect(build < .seconds(15), "index build")
85 #expect(cold < .seconds(10), "agenda refresh, cold")
86 #expect(warm < .seconds(2), "agenda refresh, warm")
87 #expect(backlinks < .milliseconds(1_500), "backlinks, 49,400 links")
88 }
89
90 /// 1,000 notes, 5,000 links.
91 @Test func backlinksGate() async throws {
92 let scratch = try Self.scratch()
93 defer { try? FileManager.default.removeItem(at: scratch) }
94 let (model, _) = try await Self.workspace(1_000, fiveLinks: 1_000, in: scratch)
95 let (found, time) = try Self.backlinks(model)
96 #expect(found > 0)
97 print("GATE 1,000 notes: backlinks over 5,000 links \(time)")
98 #expect(time < .milliseconds(150), "backlinks, 5,000 links")
99 }
100}
docs/manual/guide/10-tables.org +7 −2
@@ -43,7 +43,7 @@ With text selected, the command converts the selected lines to a table instead
4343
4444| Key | Org command | Action |
4545|---------+----------------------------+----------------------------------------------------------------------------|
46| =TAB= | =org-table-next-field= | Aligns the table and moves to the next field, skipping rules. In the last field it adds a row. |
46| =TAB= | =org-table-next-field= | Aligns the table if the row it leaves changed width, and moves to the next field, skipping rules. In the last field it adds a row. |
4747| =S-TAB= | =org-table-previous-field= | Aligns the table and moves to the previous field. |
4848| =RET= | =org-table-next-row= | Aligns the table and moves down a row in the same column. Before a rule or at the end of the table it inserts a row. |
4949
@@ -58,7 +58,12 @@ Widths count display columns, so wide characters and hidden link markup are meas
5858as they appear.
5959
6060Alignment happens when you press =TAB=, =S-TAB= or =RET= in a table and after every
61table command, not while you type. To align without moving, use Org ▸ Align Table:
61table command, not while you type. Org's =TAB= aligns only when the buffer changed
62since the last alignment; orgstar's aligns when the row it leaves no longer lines up
63with the row above (below, in the first row), so a row you changed and left some other
64way stays as it is until the next alignment. As in Org, deleting from a field that still
65ends in two spaces doesn't count as a change: =TAB= pads that field back to its width.
66To align without moving, use Org ▸ Align Table:
6267
6368| Preset | Key |
6469|--------+------------------------------|
scripts/release-ios.sh +5
@@ -10,4 +10,9 @@ PUBLISH="${ORGSTAR_PUBLISH:-1}"
1010name=orgstar
1111project=ios/Orgstar.xcodeproj
1212scheme="Orgstar iOS"
13
14# Runs before the archive.
15preflight() {
16 ORGSTAR_GATES=1 swift test -c release --filter GateTests || fail "a performance gate failed"
17}
1318. "${APPSTORE_KIT:-$(dirname "$0")/../../appstore-kit}/release-ios.sh"
scripts/release-mac.sh +2
@@ -42,6 +42,8 @@ if [ "$publish" != 0 ]; then
4242 [ "$(git branch --show-current)" = main ] || { echo "Release from main." >&2; exit 1; }
4343fi
4444
45ORGSTAR_GATES=1 swift test -c release --filter GateTests || { echo "A performance gate failed." >&2; exit 1; }
46
4547# The build number counts commits, so each release's is higher than the last's.
4648build="$(git rev-list --count HEAD)"
4749ORGSTAR_SIGN="$sign" ORGSTAR_ARCHS="arm64 x86_64" sh scripts/build-app.sh "$version" "$build" > /dev/null
scripts/release-macos.sh +2 −1
@@ -12,7 +12,7 @@ scheme="Orgstar macOS"
1212platform=macos
1313configuration=Release
1414
15# Runs before the archive, so it can only check build settings.
15# Runs before the archive, so it can only check build settings; then the performance gates.
1616preflight() {
1717 settings="$(command xcodebuild -project "$project" -scheme "$scheme" -configuration "$configuration" \
1818 -destination 'generic/platform=macOS' -showBuildSettings 2>/dev/null)" || fail "can't read the build settings of $scheme"
@@ -28,6 +28,7 @@ preflight() {
2828 ios/OrgstarQuickLook/*-macOS.entitlements ios/OrgstarSpotlight/*.entitlements; do
2929 ! grep -q temporary-exception "$entitlements" || fail "$entitlements has a temporary exception"
3030 done
31 ORGSTAR_GATES=1 swift test -c release --filter GateTests || fail "a performance gate failed"
3132}
3233
3334# Checks the built app: no Sparkle, no updater keys, no process launching, no temporary exceptions,