docs/plans/2026-11-20-parity.md

main
orgstar/docs/plans/2026-11-20-parity.md rendered · source · history · blame · raw

279 lines · 23584 bytes

20 symbols in this file

orgstar parity plan: Mac App Store and iOS vs the Developer ID build

Repo: /Users/cmc/git/krz/orgstar. Everything here comes from reading the code and the four reader reports. Nothing was built or run.

Ground rules

  • The parity target is emacs -Q. The fallbacks run emacs -Q --batch (EmacsRunner, BabelRunner). User Emacs config is not part of the target.
  • Native code lives in shared modules. Platform-neutral work goes in OrgCore: Calc, Elisp, the LaTeX and ASCII renderers, and the ODT XML writer. Code that needs a framework goes in OrgApp: JavaScriptCore, and the ODT zip if it stays there. Both are linked by all three app targets, so the Mac App Store and iOS get each feature from one change.
  • What the Developer ID build uses:
    • Native wherever the oracle tests show it matches Emacs: LaTeX, ASCII, ODT, and Calc formulas (already native first).
    • The external program when it is installed and does more than the native code: Emacs for Lisp and tables the interpreter can't handle, node for JS, gnuplot for plots, latexmk for PDF through LaTeX.
    • The native path when that program is missing. This fixes the case where a Developer ID user without Emacs can run fewer Emacs Lisp blocks than an App Store user (BabelRunner.swift:55-59).
  • Every milestone below is one merge request with its own tests and docs.

How to use the Emacs oracle tests

All oracle tests are gated on ORGSTAR_SKIP_ORACLE being unset, and on Emacs being installed where relevant.

  • Calc: add expressions to CalcTests.fixed (Tests/OrgCoreTests/CalcTests.swift:40-66). CalcOracle.run runs calc-eval with org-calc-default-modes and compares strings exactly.
    • Move cases out of unsupported() (:110) as they become supported (pi, 1/0, vmean([]), 5%, 2 3).
    • Keep #expect(skipped == []). Any new feature must match Calc or stay Unsupported.
  • Tables: TableFormulaTests.compare(_:fallbacksAllowed:) and corpusMatchesEmacs (Tests/OrgCoreTests/TableFormulaTests.swift:95-165) run org-table-recalculate / org-ctrl-c-ctrl-c through EmacsOracle.run and compare buffer text, point and error. Add tables that use the new functions.
  • Elisp: add a test to ElispTests that sends forms to EmacsOracle.evaluate(text, "(list (format \"%S\" FORM))") and compares with Elisp().eval printed by prin1-to-string.
  • LaTeX and ASCII:
    • Run EmacsOracle.evaluate(org, "(list (org-export-as 'latex))"), and 'ascii with (setq org-ascii-charset 'utf-8) (or 'ascii / 'latin1) in prelude:.
    • Compare the whole string, after normalizing only \date{\today} and the Created: / Emacs-version line, which differ by run.
    • Run over the conformance corpus Tests/OrgCoreTests/Conformance/*.org, the files ExportTests.conformance already uses, plus targeted snippets.
    • Body-only: (org-export-as 'latex nil nil t).
  • ODT: ox-odt's styles.xml is a large template, so a byte-for-byte match is not practical.
    • Oracle: org-odt-export-to-odt in a temp folder (needs zip on the dev machine), unzip content.xml.
    • Compare a reduced skeleton: element names text:h@outline-level, text:p, text:list, table:table with row/cell counts, text:a@href, text:note, draw:image, and text runs. This follows the Skeleton.reduce pattern for HTML (ExportTests.swift:44).
    • Also validate the package: mimetype is first and stored, META-INF/manifest.xml lists every part.
  • JavaScript: node is the oracle. Reuse the 8 js cases in BabelScriptTests.scriptsMatchEmacs (Tests/OrgCoreTests/BabelScriptTests.swift:24-67). Run them once through Emacs/node and once through JavaScriptBlocks, and compare the inserted results. Unit-test the util.inspect port directly against node -p 'util.inspect(X)' for a list of literals.

Milestones, highest value first

M1. Emacs Lisp interpreter growth, and Developer ID native fallback (M)

Lisp is used by table formulas, Emacs Lisp blocks, :cache, capture and diary, so this has the widest effect.

  • Fix: look up the function or special form before evaluating its arguments (Elisp.swift:203). An unknown macro such as cl-loop or pcase then throws Unsupported, which falls back, instead of #ERROR from "void variable".
  • Variables: add float-pi, pi, float-e. An unknown free variable stays a Signal, as in Emacs.
  • Math: expt sqrt exp log sin cos tan asin acos atan isnan random(seeded? no: real random) logand ash.
  • Strings:
    • string-match, match-string, match-beginning, match-end, replace-regexp-in-string, regexp-quote, string-join, string-to-char, char-to-string, string-pad, string-width, string-search, string-replace.
    • New ElispRegex.swift: translate Emacs regexp syntax (\\(, \\|, \\{n\\}, [[:alpha:]], \\b, \\w, \\s-, \\_<) into NSRegularExpression. Refuse (Unsupported) what it can't translate. Point split-string at it as well.
  • Lists, seq and cl: sort last butlast delete-dups nreverse seq-reduce seq-filter seq-map seq-uniq seq-remove cl-reduce cl-remove-if cl-remove-if-not cl-find cl-position number-to-string(floats).
  • Special forms: defun, defvar, defconst, let-alist, pcase (literal, symbol, ` and pred patterns only; otherwise Unsupported), cl-loop (for/in/from/to/collect/sum/do only), cl-incf, cl-decf.
  • Time: register the existing functions from CaptureLisp.swift:85-119 (current-time, format-time-string) and DiarySexp.swift:135-310 (calendar-*) in a shared Elisp.standardTime(). Add org-time-string-to-time, org-time-string-to-absolute, time-add, time-subtract, float-time, days-between, date-to-time, time-to-days. Make the registration in TableFormulas.evalLisp (:657) and Babel.evaluateNatively call it.
  • Developer ID:
    • In Programs.runBabel (Sources/OrgPrograms/Programs.swift:10-12): for an .emacs job when EmacsRunner.executable() == nil, return the result of Babel.evaluateNatively.
    • In DocumentSession.recalculateInEmacs: when Emacs is missing, report the native reason instead of "Emacs isn't installed".
  • Tests:
    • ElispTests oracle for each new function (regexp cases especially).
    • TableFormulaTests corpus tables using '(...) formulas with the new functions.
    • ProgramsTests case: an Emacs Lisp block runs with ORGSTAR_EMACS pointing at a missing binary.
  • Docs: docs/manual/guide/11-code-blocks.org (Emacs Lisp coverage list), 10-tables.org (Lisp formulas).

M2. Tables: keep fields written before an unsupported formula (S)

  • Native-only builds (App Store, iOS): apply formulas in Emacs's order up to the first one that throws Calc.Unsupported. Commit the fields already written, leave the rest unchanged, and report the reason with the formula's LHS. This matches Emacs's own behaviour on an error partway through (see docs/plans/2026-10-05-table-formulas.md).
  • Developer ID: keep all-or-nothing with the Emacs fallback, since Emacs then computes everything.
  • Files:
    • Sources/OrgCore/Compute/TableFormulaCommands.swift:26-48: return the partial result together with the reason.
    • New ExternalRequest case or failure-with-edits.
    • ContentView.swift:1002-1004 and MobileEditor.swift:343-346: new message text.
    • TableReason.swift.
  • Tests: TableFormulaTests with one unsupported formula after two supported ones. The first two fields change, the rest don't, and the message names the formula.
  • Docs: install.org (prose after the table), 10-tables.org, 14-ios.org:340-343.

M3. Calc: constants and missing functions (M)

All in Sources/OrgCore/Compute/Calc.swift.

  • Constants: pi and e (also phi, gamma), rounded to 12 digits as Calc's calc-eval result. Extend the variable switch at :554.
  • Statistics: vgmean vhmean vrms vmeane vcov vpcov vcorr vflat agmean; vsum/vmax/vmin/vmean with several vector or scalar arguments; vmax([])/vmin([]) once the oracle shows what Calc prints (-inf? If it's symbolic, it waits for M5).
  • Numeric: rounde roundu fdiv frac sign gcd lcm choose perm log(x,b) exp10 pow nroot hypot sinh cosh tanh arcsinh arccosh arctanh arctan2 deg rad float pfloat.
  • Function forms of operators: eq neq lt gt leq geq land lor lnot.
  • Grammar:
    • Fraction literals 1:3. Also read an unflagged 1:30 field as a fraction if the oracle confirms Calc does.
    • Postfix !.
    • Radix 16#FF.
    • Implicit multiplication 2 (x) and 2 3, if the oracle confirms Calc's reading.
    • % as percent, only if it is unambiguous against % mod. Calc uses % for mod, so check 5% in the oracle first and leave it Unsupported if it is symbolic.
  • Precision: pN for N ≤ 18 using the existing Int128 mantissa. Make precision a mode instead of static let.
  • Tests: every new function in CalcTests.fixed with integer, float and fraction arguments, and in fix/sci formats. A TableFormulaTests table using vmean($2..$4)-style multi-arg calls and ;p15.
  • Docs: 10-tables.org (list of Calc functions computed natively).

M4. Calc dates (S–M)

  • Add now() (fixed clock injected through Calc.Modes for tests), date(...), year month day weekday hour minute second yearday, incmonth incyear newmonth newyear newweek, badd bsub (weekends only; -Q has no holidays), julian, unixtime.
  • Add date × number errors as Calc gives them, floor(date), and vsum/vmean/vmin over dates.
  • Build on Days.absolute, Days.date and Days.weekday.
  • Tests: CalcTests.fixed date cases. Keep TZ=UTC, which EmacsOracle already sets.
  • Docs: 10-tables.org.

M5. Calc symbolic layer (L)

  • Add a Calc.Value.symbolic(Term) with Calc's default simplification, limited to:
    • text fields as variables (N/A + 5)
    • division by zero (x / 0, with the "Division by zero" message Calc shows)
    • inf, uinf and nan arithmetic
    • ;S mode
  • Add a printer that matches Calc's normal-language output (calc-language nil).
  • Exactness: anything whose simplified form isn't covered stays Unsupported. The oracle decides what is in scope: generate random expressions mixing a symbol with numbers and keep only the forms that match.
  • Files:
    • Calc.swift, plus a new Sources/OrgCore/Compute/CalcSymbolic.swift.
    • TableFormulas.swift:334-341: hand text fields to Calc instead of throwing "non-numeric field".
  • Tests: a CalcTests symbolic set; TableFormulaTests with blank and text cells (very common in real tables).
  • Docs: 10-tables.org.

M6. JavaScript blocks with JavaScriptCore (M–L)

New file Sources/OrgApp/JavaScriptBlocks.swift (#if canImport(JavaScriptCore)):

  • static func run(_ job: BabelJob, directory: URL) async throws -> BabelOutput?.
  • It returns nil for jobs that aren't js or javascript.
  • Shims, written in JS and bundled as a resource string:
    • require('process') and require('util'). Any other module gives node's "Cannot find module 'x'".
    • console.log/info/debug go to stdout; console.warn/error go to stderr.
    • process.stdout.write and process.stderr.write.
    • util.format (%s %d %i %f %j %o %O %%).
    • util.inspect: depth 2, quote choice, -0, arrays grouped past 6 items, circular references, Map and Set.
  • Value mode (no session): evaluate the job's input unchanged; jsWrapper already calls require('util').inspect and writes to stdout.
  • Sessions: one JSContext per key (file folder + name). Write inspect(completion value) to the result file unless output mode is on. A thrown error goes to stderr with status 1, and the context stays.
  • Uncaught errors: status 1, stderr Name: message.
  • :dir: same missing-folder check as BabelRunner.swift:63-67.
  • :cmd: ignored.
  • Timers: setTimeout/setInterval/queueMicrotask with a run loop that drains them after the script, as node does before exit. Cap at the 300 s overall limit.

Timeout and cancel:

  • Run on a dedicated Thread. On cancel or timeout, return an error, drop the context and leave the thread.
  • The public API has no execution time limit; JSContextGroupSetExecutionTimeLimit is private SPI and is not allowed in the App Store.
  • An infinite loop therefore keeps spinning one thread until the app quits. Document this.

Wiring:

  • DocumentSession.runBabel's run(_:) (DocumentSession.swift:926-940): when programs is nil, try evaluateNatively, then JavaScriptBlocks.run.
  • Developer ID: Programs.runBabel uses node when BabelRunner.installed("node"), and JSC otherwise.
  • Planner unchanged.

Tests:

  • New Tests/OrgAppTests/JavaScriptBlocksTests.swift: the 8 node oracle cases; sessions (variable persists across runs, an error keeps the session); output vs value; :var tables; hline ReferenceError as in node; require('fs') message; cancel of while(true){} returns.
  • NativeProgramsTests (AppTests.swift:983): js runs without a runner.

Docs:

  • install.org: table rows "Code blocks" and "Sessions, graphics", plus the prose after the table.
  • 11-code-blocks.org:83-104 (languages table: "js: JavaScriptCore in the App Store and iOS builds, node in the download version when installed"), :213, :486-497 (what JSC lacks: require beyond util and process, fs, Buffer, network).
  • 14-ios.org:340-343 and :437.

M7. Native LaTeX export (L)

  • New Sources/OrgCore/Export/LaTeXExport.swift: a LaTeXRenderer modelled on HTMLRenderer. It reuses ExportPreprocess, ExportOptions, ExportSource, the section selection, Coderef, CiteProcessor and ExportScope.
  • Reproduce ox-latex 9.8.7 defaults:
    • the org-latex-default-packages-alist preamble
    • article class sectioning, starred past num, levels deeper than H as lists
    • hyperref setup, title, author, date, \maketitle, \tableofcontents
    • text escaping
    • emphasis, lists, tabular with ATTR_LATEX :environment/:align/:width, captions and labels
    • verbatim src blocks, \href, \ref, \includegraphics, \footnote
    • math and #+LATEX/@@latex:/export blocks passed through
    • timestamps
    • ExportDictionary .latex
  • ExportOptions: parse LATEX_CLASS, LATEX_CLASS_OPTIONS, LATEX_HEADER, LATEX_HEADER_EXTRA, LATEX_COMPILER. Only article, report and book from the default org-latex-classes; anything else gives an error naming the class.
  • Wiring:
    • ContentView.export (:614): add latex → .tex in the native String group and take it out of the Emacs map (:662).
    • EditorCommands.swift:176-179: retitle "Export to LaTeX". Keep the app.export.latex id so key bindings still work.
    • CommandTitles.swift, string catalog.
    • AppStoreCommands.hidden: remove app.export.latex.
    • ExportSheet.formats (both lists), allowsBodyOnly.
    • iOS ExportMenu.swift Format.latex.
    • Publish.swift:43,293: org-latex-publish-to-latex.
  • Developer ID: PDF through LaTeX stays the Emacs path.
  • Tests: whole-string oracle over the conformance corpus and snippets; body-only; subtree export; ExportOptionsTests for the keywords; PublishTests for the new function.
  • Docs: install.org:61 (export row) and :71-73, 12-export.org:11-23,30-32,38,49,218,226,332-343, 14-ios.org:438.

M8. Native ASCII export (M)

  • New public ASCIIExport.document(_:settings:charset:bodyOnly:) in OrgCore, built on ASCIIText (Sources/OrgCore/Export/ASCIIText.swift).
  • Add:
    • title block, TOC
    • numbered headings with ox-ascii underlines per level and charset
    • footnote section; references currently return "" (:398)
    • ascii / latin1 / utf-8 charsets for bullets, boxes and tables
    • :justify, #+ATTR_ASCII
    • ASCII_CHARSET / #+OPTIONS
  • Keep the existing iCalendar use unchanged. The iCalendar oracle tests already cover the element layout.
  • Command ids: app.export.text becomes the native "Export to Plain Text (ASCII)". app.export.plain-text stays the attributed-string text. Merging the two is a naming decision to ask you about; the plan keeps both.
  • Wiring: same places as M7, plus org-ascii-publish-to-ascii.
  • Tests: whole-string oracle per charset over the corpus; body-only; subtree.
  • Docs: same pages as M7.

M9. Native ODT export (L)

  • Write directly from the tree, not through the HTML importer. The importer drops tables on iOS and loses structure.
  • New Sources/OrgCore/Export/ODTExport.swift produces content.xml, styles.xml and meta.xml from the parse tree:
    • text:h with outline-level and numbering
    • text:p, text:list
    • table:table with header rows
    • text:a, text:note for footnotes
    • text:span emphasis using ox-odt's style names (Emphasis, Bold, Underline, OrgCode, OrgVerbatim)
    • draw:frame/draw:image with sizes read via ImageIO
    • src blocks as OrgSrcBlock paragraphs, without highlighting (ox-odt -Q default has no htmlfontify colors? check the oracle)
  • styles.xml: a reduced styles template bundled as a resource, holding ox-odt's named styles so the structure matches.
  • Math: LaTeX fragments become images rendered with SwiftMath (OrgPresentation/LatexPreview.swift:96). ox-odt -Q without dvipng/MathToWeb leaves fragments verbatim; follow the oracle and do the same.
  • Packaging: move ZipWriter (Sources/OrgApp/DocxWriter.swift:306-352) to OrgCore as internal + @testable or package. Write mimetype first, stored.
  • Wiring: same places as M7. ODT stays whole-document only.
  • Tests: skeleton oracle as described under "How to use the Emacs oracle tests"; package-layout test; a test that the file opens with NSAttributedString(... .openDocument? no). macOS can't import ODT natively, so the test unzips and parses the XML with XMLDocument instead.
  • Docs: same pages as M7.

M10. Plots (M)

  • PlotChart.swift:
    • Interpret a :set subset: title, xlabel, ylabel, xrange, yrange, logscale x|y, grid, key off|top|bottom|left|right, xtics/ytics with a step.
    • Report an unrecognised :set, :line or :script in the result message instead of ignoring it silently.
    • Add radar plots drawn with Canvas/Path, and drop the throw at TablePlot.swift:135-136 when there is no gnuplot.
    • Add SVG output through a small SVG writer for lines, points and bars.
  • Developer ID keeps gnuplot first when installed.
  • Tests: PlotChartTests for each :set directive, radar rendering, SVG output and the warning text.
  • Docs: install.org (Plots row), 10-tables.org plot section.

M11. iOS UI parity (S each, M together)

  • Editor archive: app.archive in EditorScreen.swift:440-465 calls session.archive(from:).
  • iCalendar agenda/combined: ExportMenu.swift, using ICalendarFiles.exportEach and combine.
  • Publishing:
    • Wire Publish into EditorScreen.swift:462-465 with a project picker.
    • A security-scoped bookmark for publishingDirectory.
  • Copy as rich text: to UIPasteboard from RichTextExport.
  • app.export.html-open: Quick Look / SFSafariViewController of the temp file.
  • Clock idle approximation: time spent in the background while a clock runs, fed to ClockModel.resolveIdle on return.
  • Attach link/symlink: hide app.attach.link/symlink on iOS (reuse AppStoreCommands.hidden), or report a clear error.
  • Import agenda folders: a folder picker per Mac path, as EmacsImportView.swift:162-166 does.
  • Tests: AppTests / PublishTests with an iOS-style bookmarked folder; AppStoreCommandsTests for the hidden set.
  • Docs: 14-ios.org:435-445 ("What the Mac has that iOS doesn't"), and the export and clock sections.

M12. Lisp-adjacent extras (S–M)

  • elisp: links: run in the interpreter behind the existing TrustStore prompt (LinkFollow.swift:69-70), on all builds.
  • org-sbe in table formulas: for blocks that can run in-process (Emacs Lisp, JS after M6). Other languages stay Unsupported on App Store and iOS; on Developer ID they fall back to Emacs.
  • Docs: 09-links.org (or whichever page covers link types), 10-tables.org.

M13 (optional, not parity). New in-process languages

None of the three builds runs these today.

  • calc blocks (ob-calc) on Calc.evaluate.
  • sqlite blocks with SQLite3, emulating sqlite3 CLI output modes.

This is beyond parity, so ask you before scheduling it.

M14 (question for you). MathJax in HTML/PDF export

  • HTMLExport.swift:72-77 loads MathJax from jsdelivr, and native PDF export runs it in a WKWebView.
  • On App Store and iOS that is remote code executed by the app, and PDF math fails offline.
  • Option: bundle MathJax 3 (Apache-2.0) as a resource and inline it for PDF export only, keeping the CDN link in saved HTML. Size S–M.

Gaps that can't be closed under the constraints

Gap Why
Shell blocks (sh bash zsh fish ...) and shell: links A shell's job is spawning processes.
Python, Ruby, R blocks and their sessions No system interpreter in-process. Embedding CPython, mruby or R means shipping a large interpreter whose output differs (mruby). Not spawning, but outside this plan's scope; Python via embedded CPython is the only one worth considering (L, large binary).
C, C++, D, Java, Fortran, Clojure Need a compiler/JVM and run the built binary as a process.
PlantUML Java process.
awk Possible only by porting an awk interpreter into the app (L, low value). Not planned.
PDF through LaTeX Needs a TeX engine plus format and font files, hundreds of MB, in the bundle. Tectonic fetches support files from the network. Native print-pdf remains the substitute (AppStoreCommands.swift:13).
Full gnuplot (:script, arbitrary set) Needs gnuplot's interpreter. M10 covers a subset and reports the rest.
Arbitrary user Emacs Lisp Buffer model, org-element, user packages: open-ended. M1 grows coverage; the tail stays "runs only in Emacs" on App Store and iOS. Custom dynamic blocks (org-dblock-write:NAME) need a buffer model and are part of that tail.
Interrupting a JS infinite loop The public JavaScriptCore API has no execution time limit. A cancelled loop keeps running on its own thread.
JS that needs node (fs, child_process, http, npm modules) Not in JavaScriptCore, and network or file access would conflict with the no-download and sandbox rules.
Hard links across sandbox containers (App Store, iOS) The sandbox forbids it. Symlinks inside granted folders may work; needs a runtime check before un-hiding app.attach.symlink on the App Store build.

Decisions for you

  1. Lisp on the Developer ID build: "Emacs when installed, native when not" (the plan as written), or native first?
  2. JS on the Developer ID build: node when installed and JavaScriptCore otherwise (plan), or always JavaScriptCore so all builds give the same output?
  3. Plain-text exports: keep both plain-text (attributed-string text) and the native ox-ascii text, or merge them?
  4. Optional work: schedule M13 (calc/sqlite blocks)? Bundle MathJax (M14)?

Suggested order: M1, M2, M3, M6, M7, M9, M8, M4, M5, M10, M11, M12. That puts the four things you named first after the cheap fixes that unblock tables. M3, M6, M7, M8 and M9 don't depend on each other and can be done in parallel.