Skip to content

About

Typst math, export for Org mode

Resources

Stars

1 star

Watchers

0 watching

Forks

Latest commit

 

History

25 Commits

Folders and files

Repository files navigation

org-typst-math

Write Typst math inside Org’s math delimiters. A persistent Rust helper converts formulas to SVG previews, MathML for HTML export, or LaTeX. The community ox-typst exporter handles whole-document Typst export. Requires Emacs 30.2+ and Org 9.7.11+; no compatibility layer is included.

Installation

Nix

git clone https://github.com/DzmingLi/org-typst-math.git
cd org-typst-math
nix profile install .
nix build .#elisp --out-link result-elisp

The profile installation provides the Rust helper. Install the Elisp archives with package-install-file as described below. When the helper is on Emacs’s PATH, there is no need to set typst-client-command. You can also build the helper with nix build, or run cargo build in the development shell.

Guix

Use a recent Guix checkout that provides cargo-inputs-from-lockfile and rust-1.93 (update with guix pull if necessary). From this repository:

guix package -f guix.scm

This installs emacs-org-typst-math, Org, and the matching Rust helper as a runtime dependency. The packaged Elisp uses the helper’s absolute store path, so no PATH or typst-client-command configuration is needed. In your Guix-managed Emacs configuration, load the package:

(require 'org-typst-math)

To try it without changing your profile, including a Guix-managed Emacs:

guix shell -f guix.scm emacs -- emacs

To build without installing, run guix build -f guix.scm. The definition uses the current checkout, so run these commands again after updating it. Only Rust sources, Elisp sources and the Cargo manifests enter the source snapshot; local build artifacts are excluded.

Rust dependencies are imported directly from Cargo.lock and fetched with checksum verification before the offline build. There is no second crate list to regenerate. Whole-document Typst/PDF export still requires ox-typst separately.

Development environment and usage

flake.nix provides the development environment, pinned by flake.lock. The Nix packages support x86_64-linux, aarch64-linux, and aarch64-darwin. It includes the Rust toolchain, Emacs 31, Org, ox-typst, and the Typst CLI. Install TeX separately for LaTeX-to-PDF export. The helper links directly to Typst’s Rust libraries and does not invoke the CLI.

The helper is built with crate2nix, with a separate derivation for each crate. After changing Cargo dependencies, regenerate and commit Cargo.nix alongside Cargo.lock:

nix develop -c crate2nix generate
nix fmt -- Cargo.nix

Use the standard Org export menu in your Org buffer:

KeysOutput
C-c C-e h hHTML
C-c C-e y fTypst
C-c C-e l lLaTeX
C-c C-e l pPDF through LaTeX
C-c C-e y pPDF through ox-typst

Documents declaring TYPST_MATH: t automatically use this package’s derived exporters. Other documents retain their usual export behavior.

Enter the development shell with nix develop. It adds the project’s target/debug directory to PATH. To load a checkout in an existing Emacs session, adjust these paths:

(add-to-list 'load-path (expand-file-name "~/src/org-typst-math/lisp"))
(setq typst-client-command
      (list (expand-file-name "~/src/org-typst-math/target/debug/org-typst-math-helper")))
(require 'org-typst-math)
(require 'ox-typst nil t)  ; Optional: whole-document Typst/PDF export only.

HTML export needs only the compiled helper and the org-typst-math Elisp package. It does not require the Typst CLI or ox-typst. Use cargo build --release for an optimized helper, then update typst-client-command accordingly.

Document syntax

#+TYPST_MATH: t
#+TYPST_HEADER: #let vect(x) = math.bold(x)
#+TYPST_HEADER: #import "math-defs.typ": *

Inline $vect(v)$, or \(frac(a, b)\).

\[
sum_(k=1)^n k = (n(n+1))/2
\]

Provide the imported file or remove the import from this example. Multiple TYPST_HEADER entries are concatenated in order. Local imports resolve relative to the Org document’s directory; dependencies are reread on each HTML/LaTeX export.

$...$ and \(...\) contain inline math; $$...$$ and \[...\] contain display math. Recognition follows Org’s parser, so source blocks and verbatim text are not scanned as math.

org-typst-math-mode controls editing behavior without modifying the file. Export uses the document declaration or the :typst-math t option passed to org-export-as. Selecting typst-math-html, typst-math-latex, or typst-math-typst explicitly also enables the corresponding exporter. Load ox-typst before using the derived Typst exporter.

Displaying Unicode symbols

When org-pretty-entities is enabled, Typst math identifiers listed in org-typst-math-entities are displayed as Unicode characters inside math fragments. This is display-only: the source text, previews, and exports keep the original Typst identifiers.

#+STARTUP: entitiespretty

$alpha + beta = gamma$   ; displays as α + β = γ

Greek letters and a few common operators (such as integral, sum, dif, compose, dot, eq.not, tack.r, in, forall, exists, times, and infinity) are recognized by default. Customize M-x customize-variable RET org-typst-math-entities to add more symbols, for example ("partial" . "∂"), or set it to nil to prettify nothing. M-x org-toggle-pretty-entities and #+STARTUP: entitiespretty work as usual, and compositions are removed when org-typst-math-mode is disabled.

When org-pretty-entities-include-sub-superscripts is also enabled, math script operands are displayed smaller and raised or lowered, using Org’s script display properties. For example, x_i^2 lowers i and raises 2; sum_(k=1)^n lowers the parenthesized group and raises n. The _ and ^ markers are hidden until point is immediately before or after them; moving away hides them again. Parentheses remain visible. Simple identifiers, numbers, strings, parenthesized groups, and calls such as x^sqrt(2) are supported; incomplete groups are left unchanged. This is source display, not full mathematical typesetting. Outside math fragments, Org’s usual subscript and superscript display still applies.

Packages and processes

Package or moduleFilesDependencies
org-typst-mathlisp/org-typst-math.el, lisp/org-typst-math-export.elOrg, Emacs jsonrpc
Built-in preview modulelisp/org-typst-math-preview.elIncluded in org-typst-math

Build the org-typst-math archive:

nix build .#elisp --out-link result-elisp

Use M-x package-install-file to install org-typst-math-0.1.0.tar from result-elisp/. Configure the helper path if needed, then evaluate (require 'org-typst-math). For automatic preview toggling, install org-fragtog-plus from its separate repository. The Rust helper is built separately and is not included in the Elisp archives.

For package managers that select source files, include lisp/org-typst-math*.el and lisp/ob-typst.el. The helper connection lives in the main module; export and preview are internal modules of the same package. The optional toggling package is maintained in its own repository.

The client reuses one connection per document directory. Each HTML/LaTeX export collects all math fragments into one batch JSON-RPC request. Rust retains the font database and Typst compilation cache; there is no disk result cache or separate process per formula.

Typst export passes through math source and headers without using the helper. M-x typst-client-stop closes existing processes; subsequent requests restart them automatically. The client also provides asynchronous conversion for previews. Timeouts and transport failures discard the connection so subsequent requests can start a fresh helper. Process errors identify the executable, project directory, and stderr buffer; they are also retained in the diagnostics window.

Diagnostics retain errors from other documents and, during partial preview updates, from other formulas. Editing a formula invalidates its old preview diagnostics. Typst hints and call traces are displayed with the main error. The helper connection code lives in org-typst-math.el and is shared by preview and export. typst-client-command is a variable set with setq, not a Customize option.

Typst graphics with Org Babel

The included ob-typst backend renders ordinary Typst markup into SVG files. It uses the same persistent helper as formula previews; TYPST_MATH: t is not required. Enable it with:

(org-babel-do-load-languages 'org-babel-load-languages
                            '((typst . t)))
#+NAME: fig-demo
#+CAPTION: A Typst drawing.
#+begin_src typst :results graphics file :file demo.svg :exports results
#rect(width: 4cm, height: 2cm)[Hello]
#+end_src

See [[fig-demo]].

Execute with C-c C-c. Babel inserts an ordinary file link under #+RESULTS:. Use Org’s inline images to display that saved result. The defaults are :results file graphics and :exports results; specify :exports code to publish a code example instead. A :file ending in .svg is required (Babel’s named-block :file-ext svg also works). TYPST_HEADER entries are shared with drawings. Relative imports use the execution directory; packages must already be installed locally. :prologue and :epilogue are supported; variables and sessions are not.

HTML and Typst export use SVG. Source-block captions and backend attributes are copied to the result in the temporary export buffer; Org handles figure numbering and named references. LaTeX export converts only SVG files marked as generated by this backend to adjacent .typst.pdf files, using the Typst CLI (org-typst-babel-pdf-command). This keeps submission graphics vector based without requiring LaTeX shell escape. The generated PDF paths belong to the export machine; include the files and adjust paths for submission.

Graphics use a single preview path: execute with C-c C-c to update the SVG result, then display that result with Org inline images or org-flyimage. Editing source alone does not regenerate the image. No separate source-block preview overlays or background rendering are installed. See examples/figures.org.

Generic Typst content and link previews

The helper also accepts ordinary Typst markup, not just math bodies. typst-client-render and typst-client-render-async have the same root, preamble, item, and diagnostic contract as the math conversion API, with SVG output. They send typst/render over the same persistent connection.

(typst-client-render
 default-directory ""
 '((:id "shape" :source "#rect(width: 20pt, height: 10pt)")))

For link adapters, org-typst-math-preview-link takes an Org-owned overlay and Typst source (a string or a zero-argument function returning one). It handles asynchronous rendering, theme colour, scaling, centering, and stale results. Org owns clearing/edit invalidation. No math mode is required. Errors leave the link readable and set its help text.

For example, the optional org-quiver package can be connected in user config:

(with-eval-after-load 'org-quiver
  (setq org-quiver-preview-function
        (lambda (overlay url _link)
          (org-typst-math-preview-link
           overlay (lambda () (org-quiver-fletcher url))))))

Quiver decoding and Fletcher conversion stay in org-quiver. This package does not depend on it or duplicate its converter; any adapter producing Typst markup can use the same preview API. Preview selection is independent of the document’s export backend.

Imports resolve relative to the document directory. Package imports search TYPST_PACKAGE_PATH (a platform-separated list of package roots), then the XDG data and cache directories under typst/packages. Each root contains namespace/name/version/typst.toml. The helper never downloads packages; install them with Nix or populate the local cache first. Missing packages produce per-item diagnostics. Upgrade the Elisp module and helper together to use typst/render.

Math environments and custom blocks

Special block functions, header parameters, labels, and references belong to ox-typst. This package inherits that behavior and only handles math fragments. They do not require TYPST_MATH or loading org-typst-math.

Use the ox-typst fork for special block support. These additions are not yet in upstream ox-typst; versions without them only export special block contents. HTML and LaTeX blocks use Org’s native exporters.

Built-in previews and org-fragtog-plus

Previews are included in org-typst-math and share the persistent helper with export. They require graphical Emacs 30.2+ with SVG support. Display formulas are centered in the window’s text area; inline formulas stay in place. Centering adjusts with the window width and disappears when source is revealed.

  • M-x org-typst-preview: asynchronously preview all math in the buffer; with a prefix argument, clear previews.
  • M-x org-typst-math-preview-refresh and org-typst-math-preview-clear: explicitly refresh or clear previews.
  • M-x org-typst-math-preview-diagnostics: view errors and their locations.

org-fragtog-plus is an independent, optional package in a separate repository. It uses Org’s built-in LaTeX preview by default. Enabling org-typst-math-mode selects the buffer-local Typst backend; disabling it restores LaTeX. It neither depends on nor advises the original org-fragtog package. Do not enable both toggling modes in the same buffer.

(require 'org-typst-math)
(require 'org-fragtog-plus)
;; In an Org buffer using Typst math:
(org-typst-math-mode 1)
(org-fragtog-plus-mode 1)
(org-typst-preview) ; Optional: preview the entire buffer immediately.

Entering a formula reveals its source; leaving it restores the image, requesting a new SVG when needed. Automatic requests render only missing previews and keep existing images. Typing elsewhere while a request is running does not discard its results; editing a formula invalidates only that formula’s pending image. Automatic requests are coalesced on the next timer turn, without a fixed idle delay. Unchanged SVG output reuses the existing image object when scale and layout are unchanged. Clearing previews also cancels scheduled refreshes. Manual refresh still renders all formulas, including changes to imported macros. org-fragtog-plus-delay sets the idle delay before revealing source, in seconds (default 0). Each render automatically scales the helper’s 12pt output to the current frame’s default face size. Refresh previews after changing the default font size. Inline images reserve extra vertical space using org-typst-math-preview-inline-padding (default 6 pixels). SVG bounds include the full formula, so fractions and scripts can expand the line height.

Editing a formula invalidates its image immediately. Manual preview remains available without org-fragtog-plus. Disabling automatic toggling clears the backend’s previews and invalidates pending results.

Extending the backend

org-fragtog-plus-backend is a buffer-local function accepting ACTION and an optional FRAGMENT. Use org-fragtog-plus-set-backend to switch backends in an active buffer; it clears the previous backend’s state first.

ACTIONBehavior
fragmentReturn the Org element at point, or nil; exclude trailing whitespace
showDisplay FRAGMENT’s preview; repeated calls must not toggle it off
hideReveal FRAGMENT’s source; repeated calls must not toggle it back
clearClear buffer previews and invalidate pending results

Asynchronous backends should keep the formula at point visible as source when installing results. The Typst adapter reuses existing SVG batching, caching, and diagnostics. org-fragtog-plus itself does not need to know about Rust or Typst.

About

Typst math, export for Org mode

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages