LaTeX support for Typst, powered by Rust and WASM

Overview

LaTeX support for Typst, powered by Rust and WASM.

MiTeX processes LaTeX code into an abstract syntax tree (AST). Then it transforms the AST into Typst code and evaluates code into Typst content by eval function.

MiTeX has been proved to be practical on a large project. It has already correctly converted 32.5k equations from OI Wiki. Compared to texmath, MiTeX has a better display effect and performance in that wiki project. It is also more easy to use, since importing MiTeX to Typst is just one line of code, while texmath is an external program.

In addition, MiTeX is not only SMALL but also FAST! MiTeX has a size of just about 185 KB, comparing that texmath has a size of 17 MB. A not strict but intuitive comparison is shown below. To convert 32.5k equations from OI Wiki, texmath takes about 109s, while MiTeX WASM takes only 2.28s and MiTeX x86 takes merely 0.085s.

Thanks to @Myriad-Dreamin, he completed the most complex development work: developing the parser for generating AST.

MiTeX as a Typst Package

  • Use mitex-convert to convert LaTeX code into Typst code in string.
  • Use mi to render an inline LaTeX equation in Typst.
  • Use mitex(numbering: none, supplement: auto, ..) or mimath to render a block LaTeX equation in Typst.
  • Use mitext to render a LaTeX text in Typst.

PS: #set math.equation(numbering: "(1)") is also valid for MiTeX.

Following is a simple example of using MiTeX in Typst:

#import "@preview/mitex:0.2.4": *

#assert.eq(mitex-convert("\alpha x"), "alpha  x ")

Write inline equations like #mi("x") or #mi[y].

Also block equations (this case is from #text(blue.lighten(20%), link("https://katex.org/")[katex.org])):

#mitex(`
  \newcommand{\f}[2]{#1f(#2)}
  \f\relax{x} = \int_{-\infty}^\infty
    \f\hat\xi\,e^{2 \pi i \xi x}
    \,d\xi
`)

We also support text mode (in development):

#mitext(`
  \iftypst
    #set math.equation(numbering: "(1)", supplement: "equation")
  \fi

  \section{Title}

  A \textbf{strong} text, a \emph{emph} text and inline equation $x + y$.

  Also block \eqref{eq:pythagoras}.

  \begin{equation}
    a^2 + b^2 = c^2 \label{eq:pythagoras}
  \end{equation}
`)

example

MiTeX as a CLI Tool

Installation

Install the latest nightly version by cargo install --git https://github.com/mitex-rs/mitex mitex-cli.

Usage

mitex compile main.tex
# or (same as above)
mitex compile main.tex mitex.typ

MiTeX as a Web App

MiTeX Online Math Converter

We can convert LaTeX equations to Typst equations in web by wasm. https://mitex-rs.github.io/mitex/

Underleaf

We made a proof of concept online tex editor to show our conversion speed in text mode. The PoC loads files from a git repository and then runs typst compile in browser. As you see, each keystroking get response in preview quickly.

https://mitex-rs.github.io/mitex/tools/underleaf.html

underleaf.mp4

Implemented Features

  • User-defined TeX (macro) commands, such as \newcommand{\mysym}{\alpha}.
  • LaTeX equations support.
    • Coloring commands (\color{red} text, \textcolor{red}{text}).
    • Support for various environments, such as aligned, matrix, cases.
  • Basic text mode support, you can use it to write LaTeX drafts.
    • \section, \textbf, \emph.
    • Inline and block math equations.
    • \ref, \eqref and \label.
    • itemize and enumerate environments.
    • figure, table and tabular environments.

Features to Implement

  • Pass command specification to MiTeX plugin dynamically. With that you can define a typst function let myop(it) = op(upright(it)) and then use it by \myop{it}.
  • Package support, which means that you can change set of commands by telling MiTeX to use a list of packages.
  • Better text mode support, such as figure, algorithm and description environments.

To achieve the latter two goals, we need a well-structured architecture for the text mode, along with intricate work. Currently, we don't have very clear ideas yet. If you are willing to contribute by discussing in the issues or even submitting pull requests, your contribution is highly welcome.

Differences between MiTeX and other solutions

MiTeX has different objectives compared to texmath (a.k.a. pandoc):

  • MiTeX focuses on rendering LaTeX content correctly within Typst, leveraging the powerful programming capabilities of WASM and typst to achieve results that are essentially consistent with LaTeX display.
  • texmath aims to be general-purpose converters and generate strings that are more human-readable.

For example, MiTeX transforms \frac{1}{2}_3 into frac(1, 2)_3, while texmath converts it into 1 / 2_3. The latter's display is not entirely correct, whereas the former ensures consistency in display.

Another example is that MiTeX transforms (\frac{1}{2}) into \(frac(1, 2)\) instead of (frac(1, 2)), avoiding the use of automatic Left/Right to achieve consistency with LaTeX rendering.

Certainly, the greatest advantage is that you can directly write LaTeX content in Typst without the need for manual conversion!

Submitting Issues

If you find missing commands or bugs of MiTeX, please feel free to submit an issue here.

Contributing to MiTeX

Currently, MiTeX maintains following three parts of code:

For a translation process, for example, we have:

$(num)/(den)$))">
\frac{1}{2}

===[parser]===> AST ===[converter]===>

#eval("$frac(1, 2)$", scope: (frac: (num, den) => $(num)/(den)$))

You can use the #mitex-convert() function to get the Typst Code generated from LaTeX Code.

Add missing TeX commands

Even if you don't know Rust at all, you can still add missing TeX commands to MiTeX by modifying specification files, since they are written in typst! You can open an issue to acquire the commands you want to add, or you can edit the files and submit a pull request.

In the future, we will provide the ability to customize TeX commands, which will make it easier for you to use the commands you create for yourself.

Develop the parser and the converter

See CONTRIBUTING.md.

Comments
  • Nesting math and normal text in LaTeX is NOT correctly rendered

    Nesting math and normal text in LaTeX is NOT correctly rendered

    #import "@preview/mitex:0.2.1": *
    #set math.equation(numbering: "(1)", supplement: [#text(blue)[*Eq.*]])
    
    #mitext(`
        \begin{align}
          \text{Stokes formula for Manifold $\mathcal M$}\quad \int_{\mathcal M}\mathrm{d}\omega&=\int_{\partial\mathcal M}\omega
        \end{align}
    `)
    

    Resulting 2024-02-15_16-34 where the nested math \mathcal M$ is not correctly rendered.

    While

    #import "@preview/mitex:0.2.1": *
    #set math.equation(numbering: "(1)", supplement: [#text(blue)[*Eq.*]])
    
    #mitext(`
        \begin{align}
          \text{Stokes formula for Manifold}~$\mathcal M$\quad \int_{\mathcal M}\mathrm{d}\omega&=\int_{\partial\mathcal M}\omega
        \end{align}
    `)
    

    is OK

    help wanted T Converter 
    opened by xiaodong-hu 9
  • Parser Inconsistency for Several Math Expressions

    Parser Inconsistency for Several Math Expressions

    Hi, after several days trial of mitex, I found several annoying inconsistencies, even for standard math notation:

    1. In math, we use square bracket [ and parenthesis ( to represent the close and open set. But when I try to convert my notes including something like $[0,1,\cdots, N_s)$ blablabla, I got serious parse error (collapse to one line)

    It seems because the parser found some unclosed/unpaired bracket. If so, that is really stupid to me (we should be free to use any symbol in math mode).

    1. The vertical line in latex is somewhat parse to wrong symbol, for example, Bloch states$|\boldsymbol k\rangle$ is wrongly parsed by mitex: I got extra spaces between k and the vertical line. But if I try to make it converting from $\ket{\boldsymbol k}$ by explicitly telling mitex what the composite symbol is (here is the ket state), then the conversion is OK.

    In latex at least $|\boldsymbol k\rangle$ and $\ket{\boldsymbol k}$ looks the same, without knowing the meaning for the composite symbol |...\rangle, and there are indeed some situation when $\bra{...}$ or $\ket{...}$ or $\braket{...}$ cannot handle, that is why most people still control the size of vertical line | and the size of angle bracket \langle and \rangle by hand.

    T Parser 
    opened by xiaodong-hu 8
  • Provide a native CLI program to convert LaTeX source into typst source.

    Provide a native CLI program to convert LaTeX source into typst source.

    If I get it correctly, for the time being, mitex only works as a WASM module and thus only works on the typst web app, but not for the CLI.

    It would be better to provide a CLI program that runs like:

    mitex -i foo.tex -o foo.typ
    

    Then we can deal with the typst source with typst-cli.

    Another benefit of this is that we can easily build a testset with a bunch of TeX sources, which will largely assure the quality and stability of mitex.

    enhancement 
    opened by KDr2 8
  • Correct `\mathbf` Rendering to Regular Fonts

    Correct `\mathbf` Rendering to Regular Fonts

    Hi, I found that that both \mathbf . and \mathbf{...} cannot be correctly rendered in desired form as in LaTeX (bold AND regular). For example,

    #import "@preview/mitex:0.2.2": *
    
    #mitext(`Reciprocal vector is $\mathbf G$ or $\mathbf{G}$`)
    

    gives 2024-03-20_14-13

    But in LaTeX, it should be 2024-03-20_14-15

    NOTE: \bm (as well as \boldsymbol(please also add support for this command)) behaves different from \mathbf!


    And here is one more tricky thing:

    See https://tex.stackexchange.com/questions/294561/using-textbf-vs-mathbf-in-math-mode. Precisely, \mathbf{...} and \textbf{...} are different in LaTeX, in that \mathbf{...} will remove ALL blank spaces within its arguments. So probably a more correct rendering is to parse, for example, for the LaTeX code:

    $\sum_{i\in\mathcal I}\mathbf{Op With Space}=\text{blablabla}$
    

    2024-03-20_15-10

    as the Typst code:

    $ sum_(i in cal(I))bold(#"Op With Spaces".replace(" ", ""))="blablabla" $ 
    

    2024-03-20_15-18

    I think this clearly demonstrate how to fix the \mathbf rendering problem : )

    Thanks for your help!

    bug T Spec 
    opened by xiaodong-hu 5
  • dev: remove unsafe code

    dev: remove unsafe code

    I'd like your opinions on these changes, specifically, was any of this the unsafe code used for performance reasons and are the safe replacements too slow?

    opened by mattfbacon 5
  • Commands to add for OI Wiki test

    Commands to add for OI Wiki test

    Scanned by script

    • [x] \notag
    • [x] \brack
    • [x] \triangle
    • [x] \impliedby
    • [x] \LaTeX
    • [x] \space
    • [x] \lnot
    • [x] \mathop
    • [x] \vert
    • [x] \middle
    • [x] \lvert
    • [x] \rvert
    • [x] \lVert
    • [x] \Bbb
    • [x] \implies
    • [x] \boxed
    • [x] \checkmark
    • [x] \substack
    • [x] \dotsb
    • [x] \dbinom
    • [x] \*
    • [x] \wedge
    • [x] \subsetneqq
    • [x] \emptyset
    • [x] \pod
    • [x] \lor
    • [x] \cr
    • [x] \tag
    • [x] \varphi*
    • [x] \brace
    • [x] \begin{alignedat}
    T Spec 
    opened by Myriad-Dreamin 4
  • refactor: improve formula parser

    refactor: improve formula parser

    I have refactored the parser and added some tests for formulas.

    During testing, I find a bug:

    https://github.com/mitex-rs/mitex/blob/b85675ab1eba8774894948091432765fb433f1cc/crates/mitex/src/lib.rs#L1151-L1156

    And two optional semantic errors to handle:

    https://github.com/mitex-rs/mitex/blob/b85675ab1eba8774894948091432765fb433f1cc/crates/mitex/src/lib.rs#L1157-L1168

    opened by Myriad-Dreamin 3
  • feat: add support for `\(\)` and `\[\]` instead of `$`'s

    feat: add support for `\(\)` and `\[\]` instead of `$`'s

    Not too sure on some of the organization, particularly treating \( and \[ as dollars syntactically.

    #import "packages/mitex/mitex.typ": *
    
    = Converted
    
    #let test_text = "
      \\(1 + 2\\)
      \\[1 + 2\\]
    "
    
    #raw(mitex-convert(mode: "text", test_text))
    = Rendered
    
    #eval(
      mitex-convert(mode: "text", test_text), mode: "markup", scope: mitex-scope,
    )
    

    gives

    image

    Closes #124

    opened by Tweoss 3
  • Load resources from inside mitex

    Load resources from inside mitex

    Is it possible to load an image in a iftypst block?

    I've been able to use typst.ts with mapShadow in the browser to render images. However, when I try to put this image in a iftypst block, I get a "failed to load file (access denied)", trace: [Call(Some("mimath"))], hints: ["cannot read file outside of project root" error.

    It seems to me that the web demo is able to import both a bibliography and another template file. However, I cannot figure out where inpackages/mitex-web/src this virtual file system is handled. It appears that there is a VFS for the sidebar directory view, but I cannot tell how this integrates with mitex. Is there some documentation on this?

    opened by Tweoss 3
  • Add detailed Installation Instructions to README

    Add detailed Installation Instructions to README

    I am genuinely impressed with potential of this project and excited about the possibilities it offers. However, I've encountered a bit of a roadblock. As a new user, I'm unsure about the installation process, as the current README file doesn't include an installation section. This has made it challenging for me to get started with the project.

    Could you please consider adding an installation guide to the README?

    opened by szsdk 3
  • `\rangle` error for inline LaTeX `#mi`

    `\rangle` error for inline LaTeX `#mi`

    version: 0.2.4: problem:

    #mi("\langle{w_1}\rangle")
    #mitex(`\langle{w_1}\rangle`)
    

    is different, and #mi fail to generate \rangle.

    by the way, could anyone tell me that how to present $\langle \rangle$ in typst?

    opened by Yiyi-philosophy 2
  • Weird spacing in multi-line equations

    Weird spacing in multi-line equations

    When using explicit equation environments (such as equation or aligned), the spacing around the equation changes when the equation has multiple lines. This is not the case when just using $$ ... $$. For example

    Lorem ipsum dolor sit amet consetetur sadipscing elitr sed diam nonumy
    
    % Left side in image (this is shifted upwards)
    \begin{aligned}
      a^2 + b^2 = c^2 \\
      a^2 + b^2 = c^2
    \end{aligned}
    
    Lorem ipsum dolor sit amet consetetur sadipscing elitr sed diam nonumy
    
    % Right side in image (this is what I would expect)
    $$ 
      a^2 + b^2 = c^2 \\
      a^2 + b^2 = c^2
    $$
    
    Lorem ipsum dolor sit amet consetetur sadipscing elitr sed diam nonumy
    

    Comparison

    opened by EpicEricEE 0
  • Left...Right Groups Update

    Left...Right Groups Update

    The new version of typst has fixed the weird spacing in left...right pairs, see Fixed weak spacing in lr groups in https://github.com/typst/typst/releases/, for example the bra-ket symbol, as well as \mid in quantum mechanics.

    Please update the conversion to correct typst command for correct rendering.

    opened by xiaodong-hu 0
  • LaTeX \[ ... \] preferable to $$ ... $$.

    LaTeX \[ ... \] preferable to $$ ... $$.

    At https://mitex-rs.github.io/mitex/tools/underleaf.html, \[ ... \] (which is preferable to $$ ... $$, and used by many) is not parsed correctly. I put two \ so that it renders correctly but in LateX there is only one. See https://tex.stackexchange.com/questions/503/why-is-preferable-to

    opened by EricJC24 0
  • dev: work on arxiv.2301.00029

    dev: work on arxiv.2301.00029

    Problematic cases:

    \topmargin 0.0cm
    \oddsidemargin 0.2cm
    \textwidth 16cm 
    \textheight 21cm
    \footskip 1.0cm
    
    \newtheorem{mydef}{Definition}
    
    \makeatletter
    \renewcommand*\env@matrix[1][\arraystretch]{%
      \edef\arraystretch{#1}%
      \hskip -\arraycolsep
      \let\@ifnextchar\new@ifnextchar
      \array{*\c@MaxMatrixCols c}}
    \makeatother
    
    \newenvironment{sciabstract}{%
    \begin{quote} \bf}
    {\end{quote}}
    
    \bibliography{References}
    
    opened by Myriad-Dreamin 0
  • [Bug] Missing symbols

    [Bug] Missing symbols

    These LaTeX symbols are missing

    \gtreqqless
    \nsubseteqq
    \nleqslant
    \nshortmid
    \smallfrown
    \shortmid
    \gtrapprox
    \thickapprox
    \nshortparallel
    \nsupseteqq
    \ngeqq
    \gvertneqq
    \lvertneqq
    \not
    \nleqq
    
    opened by ParaN3xus 0
Transpile CommonMark Markdown to Typst, from within Typst!

#set document(title: "cmarker.typ") #set page(numbering: "1", number-align: center) #set text(lang: "en") #align(center, text(weight: 700, 1.75em)[cma

Sabrina Jewson 6 Oct 28, 2023
🏭 Convert Markdown documents into themed HTML pages with support for code syntax highlighting, LaTeX and Mermaid diagrams.

Marky Markdown Magician ?? Features Hot reload previewing ?? Conversion to HTML / PDF ?? Themes! ✨ Extensions - Math, diagrams, syntax-highlighting ??

Vadim 12 Feb 19, 2023
Latex template handler using Rust

Latex template handler using Rust All the templates used by this program are stored in another GitHub repository. Dependencies rust & cargo How to use

Johan RodrĂ­guez 2 Oct 19, 2022
A transpiled superset of TeX for writing LaTeX.

LiA A transpiled superset of TeX for writing LaTeX. This is more for my personal use however you're welcome to use it or contribute. These added featu

Jasper 62 Jan 5, 2023
Make beautiful colored code listings in LaTeX with the power of TreeSitter.

What is this? This is a CLI tool that consumes TreeSitter's output and transforms it into LaTeX code that will produce syntax-colored code listing. If

Tomáš Lebeda 11 Sep 4, 2023
run Typst in JavaScriptWorld.

Typst.ts Typst.ts allows you to independently run the Typst compiler and exporter (renderer) in your browser. You can: locally run the compilation via

null 9 Apr 18, 2023
Shell Escape for Typst typesetting system. Linux Only.

Shell Escape for Typst This is a simple shell escape for Typst. It allows you to run shell commands directly from Typst compiler. That said, it does n

Nikolay Stepanov 4 Jun 7, 2023
Packages for Typst.

Typst Packages An experimental package repository for Typst. A searchable list of all packages that were submitted here is available in the official d

Typst 91 Jul 4, 2023
An mdBook backend to output Typst markup, pdf, png, or svg

mdbook-typst mdbook-typst is a backend for mdBook. The backend converts the book to Typst markup and can output any format Typst can (currently pdf, p

Christian Legnitto 18 Dec 16, 2023
A tool to compare how Typst documents would look using different fonts or font variants.

typst-font-compare A tool to compare how Typst documents would look using different fonts or font variants. Installation cargo install --path . Usage

null 3 Feb 15, 2024
Verifiable and confidential computation based on ZKP and FHE, powered by risc0 zkVM.

zkFHE Verifiable and confidential computation based on ZKP and FHE, powered by risc0 zkVM. A PoC to demonstrate an approach for private computation on

Emiliano Bonassi 29 Apr 25, 2023
Rust-powered CLI tool designed to simplify and streamline the release process with help of ChatGPT

$ releasecraftsman ????‍♂️?? Automate Your Release Process with Precision and Ease. ?? Features Generate well-crafted release notes using GPT-3.5 and

Tornike Gomareli 7 Sep 21, 2023
🛠️ An experimental functional systems programming language, written in Rust and powered by LLVM as a backend.

An experimental functional systems programming language, written in Rust, and powered by LLVM as a backend. ?? Goal: The intent is to create a program

codex 3 Nov 15, 2023
A programming and system administration assistant, powered by chatGPT

TermGPT Interact with ChatGPT from your terminal! ?? ?? Install Cargo cargo install termgpt termgpt --help From source git clone [email protected]:bahdot

Gokul 5 May 11, 2023
epNFTs, the first partial program-owned NFT Standard powered by Instruction Introspection and Transfer Hooks!

epNFT Standard: A Comprehensive Guide Introduction to epNFTs Welcome to the epNFT-standard repository, where we explore the first program-owned NFT st

epPlex 6 Mar 1, 2024
A blazingly fast Insertion Sort and Quick Sort visualizer built with Rust and WASM.

sortysort A blazingly fast Insertion Sort and Quick Sort visualizer built with Rust and WASM. Try it in your browser from here Testing locally cargo r

null 3 Jan 28, 2022
UpVent Website (Powered by Rust + Svelte & Fernet Branca).

UpVent Website Source Build Status Description This is the source code for the UpVent's website under upvent.codes. Development occurs on the master b

UpVent 3 Dec 2, 2022
A syntax highlighter for Node powered by Tree Sitter. Written in Rust.

tree-sitter-highlight A syntax highlighter for Node.js powered by Tree Sitter. Written in Rust. Usage The following will output HTML: const treeSitter

Devon Govett 211 Dec 20, 2022
An Intel HAXM powered, protected mode, 32 bit, hypervisor addition calculator, written in Rust.

HyperCalc An Intel HAXM powered, protected mode, 32 bit, hypervisor addition calculator, written in Rust. Purpose None ?? . Mostly just to learn Rust

Michael B. 2 Mar 29, 2022