docs/plans/2026-11-20-parity.md
279 lines · 23584 bytes
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 runemacs -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.runrunscalc-evalwithorg-calc-default-modesand 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 stayUnsupported.
- Move cases out of
- Tables:
TableFormulaTests.compare(_:fallbacksAllowed:)andcorpusMatchesEmacs(Tests/OrgCoreTests/TableFormulaTests.swift:95-165) runorg-table-recalculate/org-ctrl-c-ctrl-cthroughEmacsOracle.runand compare buffer text, point and error. Add tables that use the new functions. - Elisp: add a test to
ElispTeststhat sends forms toEmacsOracle.evaluate(text, "(list (format \"%S\" FORM))")and compares withElisp().evalprinted byprin1-to-string. - LaTeX and ASCII:
- Run
EmacsOracle.evaluate(org, "(list (org-export-as 'latex))"), and'asciiwith(setq org-ascii-charset 'utf-8)(or'ascii/'latin1) inprelude:. - Compare the whole string, after normalizing only
\date{\today}and theCreated:/ Emacs-version line, which differ by run. - Run over the conformance corpus
Tests/OrgCoreTests/Conformance/*.org, the filesExportTests.conformancealready uses, plus targeted snippets. - Body-only:
(org-export-as 'latex nil nil t).
- Run
- ODT: ox-odt's styles.xml is a large template, so a byte-for-byte match is not practical.
- Oracle:
org-odt-export-to-odtin a temp folder (needszipon the dev machine), unzipcontent.xml. - Compare a reduced skeleton: element names
text:h@outline-level,text:p,text:list,table:tablewith row/cell counts,text:a@href,text:note,draw:image, and text runs. This follows theSkeleton.reducepattern for HTML (ExportTests.swift:44). - Also validate the package:
mimetypeis first and stored,META-INF/manifest.xmllists every part.
- Oracle:
- 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 throughJavaScriptBlocks, and compare the inserted results. Unit-test theutil.inspectport directly againstnode -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 ascl-looporpcasethen throwsUnsupported, which falls back, instead of#ERRORfrom "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. Pointsplit-stringat 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,`andpredpatterns only; otherwise Unsupported),cl-loop(for/in/from/to/collect/sum/doonly),cl-incf,cl-decf. - Time: register the existing functions from
CaptureLisp.swift:85-119(current-time,format-time-string) andDiarySexp.swift:135-310(calendar-*) in a sharedElisp.standardTime(). Addorg-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 inTableFormulas.evalLisp(:657) andBabel.evaluateNativelycall it. - Developer ID:
- In
Programs.runBabel(Sources/OrgPrograms/Programs.swift:10-12): for an.emacsjob whenEmacsRunner.executable() == nil, return the result ofBabel.evaluateNatively. - In
DocumentSession.recalculateInEmacs: when Emacs is missing, report the native reason instead of "Emacs isn't installed".
- In
- Tests:
ElispTestsoracle for each new function (regexp cases especially).TableFormulaTestscorpus tables using'(...)formulas with the new functions.ProgramsTestscase: an Emacs Lisp block runs withORGSTAR_EMACSpointing 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 (seedocs/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
ExternalRequestcase or failure-with-edits. ContentView.swift:1002-1004andMobileEditor.swift:343-346: new message text.TableReason.swift.
- Tests:
TableFormulaTestswith 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:
piande(alsophi,gamma), rounded to 12 digits as Calc'scalc-evalresult. Extend the variable switch at:554. - Statistics:
vgmean vhmean vrms vmeane vcov vpcov vcorr vflat agmean;vsum/vmax/vmin/vmeanwith 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 unflagged1:30field as a fraction if the oracle confirms Calc does. - Postfix
!. - Radix
16#FF. - Implicit multiplication
2 (x)and2 3, if the oracle confirms Calc's reading. %as percent, only if it is unambiguous against%mod. Calc uses%for mod, so check5%in the oracle first and leave it Unsupported if it is symbolic.
- Fraction literals
- Precision:
pNfor N ≤ 18 using the existing Int128 mantissa. Makeprecisiona mode instead ofstatic let. - Tests: every new function in
CalcTests.fixedwith integer, float and fraction arguments, and in fix/sci formats. ATableFormulaTeststable usingvmean($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 throughCalc.Modesfor tests),date(...),year month day weekday hour minute second yearday,incmonth incyear newmonth newyear newweek,badd bsub(weekends only;-Qhas no holidays),julian,unixtime. - Add date × number errors as Calc gives them,
floor(date), andvsum/vmean/vminover dates. - Build on
Days.absolute,Days.dateandDays.weekday. - Tests:
CalcTests.fixeddate cases. KeepTZ=UTC, whichEmacsOraclealready 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,uinfandnanarithmetic;Smode
- text fields as variables (
- 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 newSources/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')andrequire('util'). Any other module gives node's "Cannot find module 'x'".console.log/info/debuggo to stdout;console.warn/errorgo to stderr.process.stdout.writeandprocess.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;
jsWrapperalready callsrequire('util').inspectand writes to stdout. - Sessions: one
JSContextper key (file folder + name). Writeinspect(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 asBabelRunner.swift:63-67.:cmd: ignored.- Timers:
setTimeout/setInterval/queueMicrotaskwith 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;
JSContextGroupSetExecutionTimeLimitis 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'srun(_:)(DocumentSession.swift:926-940): whenprogramsis nil, tryevaluateNatively, thenJavaScriptBlocks.run.- Developer ID:
Programs.runBabeluses node whenBabelRunner.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;:vartables;hlineReferenceError as in node;require('fs')message; cancel ofwhile(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:requirebeyondutilandprocess,fs,Buffer, network).14-ios.org:340-343and:437.
M7. Native LaTeX export (L)
- New
Sources/OrgCore/Export/LaTeXExport.swift: aLaTeXRenderermodelled onHTMLRenderer. It reusesExportPreprocess,ExportOptions,ExportSource, the section selection,Coderef,CiteProcessorandExportScope. - Reproduce ox-latex 9.8.7 defaults:
- the
org-latex-default-packages-alistpreamble articleclass sectioning, starred pastnum, levels deeper than H as listshyperrefsetup, title, author, date,\maketitle,\tableofcontents- text escaping
- emphasis, lists,
tabularwithATTR_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
- the
ExportOptions: parseLATEX_CLASS,LATEX_CLASS_OPTIONS,LATEX_HEADER,LATEX_HEADER_EXTRA,LATEX_COMPILER. Onlyarticle,reportandbookfrom the defaultorg-latex-classes; anything else gives an error naming the class.- Wiring:
ContentView.export(:614): addlatex→.texin the native String group and take it out of the Emacs map (:662).EditorCommands.swift:176-179: retitle "Export to LaTeX". Keep theapp.export.latexid so key bindings still work.CommandTitles.swift, string catalog.AppStoreCommands.hidden: removeapp.export.latex.ExportSheet.formats(both lists),allowsBodyOnly.- iOS
ExportMenu.swiftFormat.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;
ExportOptionsTestsfor the keywords;PublishTestsfor 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 onASCIIText(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-8charsets for bullets, boxes and tables:justify,#+ATTR_ASCIIASCII_CHARSET/#+OPTIONS
- Keep the existing iCalendar use unchanged. The iCalendar oracle tests already cover the element layout.
- Command ids:
app.export.textbecomes the native "Export to Plain Text (ASCII)".app.export.plain-textstays 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.swiftproducescontent.xml,styles.xmlandmeta.xmlfrom the parse tree:text:hwith outline-level and numberingtext:p,text:listtable:tablewith header rowstext:a,text:notefor footnotestext:spanemphasis using ox-odt's style names (Emphasis,Bold,Underline,OrgCode,OrgVerbatim)draw:frame/draw:imagewith sizes read via ImageIO- src blocks as
OrgSrcBlockparagraphs, without highlighting (ox-odt-Qdefault 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-Qwithout dvipng/MathToWeb leaves fragments verbatim; follow the oracle and do the same. - Packaging: move
ZipWriter(Sources/OrgApp/DocxWriter.swift:306-352) to OrgCore asinternal+@testableorpackage. Writemimetypefirst, 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 withXMLDocumentinstead. - Docs: same pages as M7.
M10. Plots (M)
PlotChart.swift:- Interpret a
:setsubset:title,xlabel,ylabel,xrange,yrange,logscale x|y,grid,key off|top|bottom|left|right,xtics/yticswith a step. - Report an unrecognised
:set,:lineor:scriptin the result message instead of ignoring it silently. - Add radar plots drawn with
Canvas/Path, and drop the throw atTablePlot.swift:135-136when there is no gnuplot. - Add SVG output through a small SVG writer for lines, points and bars.
- Interpret a
- Developer ID keeps gnuplot first when installed.
- Tests:
PlotChartTestsfor each:setdirective, radar rendering, SVG output and the warning text. - Docs:
install.org(Plots row),10-tables.orgplot section.
M11. iOS UI parity (S each, M together)
- Editor archive:
app.archiveinEditorScreen.swift:440-465callssession.archive(from:). - iCalendar agenda/combined:
ExportMenu.swift, usingICalendarFiles.exportEachandcombine. - Publishing:
- Wire
PublishintoEditorScreen.swift:462-465with a project picker. - A security-scoped bookmark for
publishingDirectory.
- Wire
- Copy as rich text: to
UIPasteboardfromRichTextExport. app.export.html-open: Quick Look /SFSafariViewControllerof the temp file.- Clock idle approximation: time spent in the background while a clock runs, fed to
ClockModel.resolveIdleon return. - Attach link/symlink: hide
app.attach.link/symlinkon iOS (reuseAppStoreCommands.hidden), or report a clear error. - Import agenda folders: a folder picker per Mac path, as
EmacsImportView.swift:162-166does. - Tests:
AppTests/PublishTestswith an iOS-style bookmarked folder;AppStoreCommandsTestsfor 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 existingTrustStoreprompt (LinkFollow.swift:69-70), on all builds.org-sbein 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.
calcblocks (ob-calc) onCalc.evaluate.sqliteblocks withSQLite3, emulatingsqlite3CLI output modes.
This is beyond parity, so ask you before scheduling it.
M14 (question for you). MathJax in HTML/PDF export
HTMLExport.swift:72-77loads 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
- Lisp on the Developer ID build: "Emacs when installed, native when not" (the plan as written), or native first?
- JS on the Developer ID build: node when installed and JavaScriptCore otherwise (plan), or always JavaScriptCore so all builds give the same output?
- Plain-text exports: keep both
plain-text(attributed-string text) and the native ox-asciitext, or merge them? - 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.