Hacker Newsnew | past | comments | ask | show | jobs | submitlogin
KaTeX – The fastest math typesetting library for the web (katex.org)
203 points by haneefmubarak on Oct 10, 2020 | hide | past | favorite | 87 comments


KaTeX is great, but I long for a system that:

1. Can be rendered server-side without a heavy runtime (ideally written in C/C++/Rust/Whatever instead of JS).

2. Has a well defined output AST, so that the output can be manipulated (e.g. realtime visual equation editing).

3. Is accessible to the visually impared.

Actually, we have such a system: MathML. And its a W3C standard to boot. The only reason why we have to rely on slow JS hacks like KaTeX and MathJax is because of Chrome. Google hates disabled people.


I don't know if I'm reading [1] correctly but it appears that Google is finally working on implementing MathML in Chromium. There have been multiple commits and updates to this bug in 2020, especially in September.

Edit: It's not being implemented by Google. It's a sponsored effort because Google couldn't be bothered. [2]

1: https://bugs.chromium.org/p/chromium/issues/detail?id=6606

2: https://mathml.igalia.com


Igalia seems like such a great company. They are doing lots of important and exciting things in open source. Sure, they get paid for it and all that, but it seems like such a cool idea. I am glad it seems to work for them


The bad accessibility of math notation and math content is one of the main reasons there are very few visually impaired people in STEM, one of the main reasons why I'm doing code and not physics, and why Firefox is given as the accessibility default in web.


Actually often I wish that AI papers contained code instead of math so that it's clearer how it can be implemented, and how the variables are used. It would make the papers a bit longer, but implementations easier to understand.


> Actually often I wish that AI papers contained code instead of math so that it's clearer how it can be implemented

That's insanity. Sure, code is a nice addition, but it does not convey the same information as the math does.

It's akin to asking to replace an engineer's design of a bridge with a scale model.


I think this is more akin to construction workers asking for blueprints rather than cad models.

As someone who hasn't actively done formal math in a couple of decades the slog of relearning syntax to read papers about code can be off putting. I understand that this makes me a barbarian. However code is really the lingua franca we use as an industry but in papers it is treated exactly as you say a nice addition.


> I think this is more akin to construction workers asking for blueprints rather than cad models.

No, because those aim to express the same thing, albeit with different limitations and practical considerations. Code and math are entirely separate things.

> As someone who hasn't actively done formal math in a couple of decades the slog of relearning syntax to read papers about code can be off putting.

Surely the syntax is an incredibly minor part of it all?

> However code is really the lingua franca we use as an industry but in papers it is treated exactly as you say a nice addition.

Code is an implementation detail. Papers express ideas, not implementations.


Not quite the same field, but see https://news.ycombinator.com/item?id=24649992 for an article about PLT (programming language theory) notation.


Working daily with a blind scientist, I am translating the equations from old papers without good OCR in Fortran to discuss them. I haven't found a better way, but we would definitely appreciate more accessible content.


You're translating into fortran? Why?


Because Fortran is FORmula TRANslator and it is very easy to express complex equations with it. It the lingua franca of scientific computing.


TIL. I'm curious what Fortran buys you over, say, Julia.


We simply master Fortran because of all the number crunching we are doing, nothing more.


because it is powerful, fast, simple, object oriented, while being natively parallel, on both shared and distributed architecture.


Would mathematical[0] satisfy at least the first two requirement? I just found about it from the MathJax post today.

[0] https://github.com/gjtorikian/mathematical


FYI, LaTeX notation is used by many blind people to express math ideas even if they don't actually use LaTeX for typesetting. (I personally know two programmers, one math teacher and one scientist who are using it with a braille display on daily basis.) So it's not totally anti-accessibility.


KaTeX can be generated server-side (no JS on client-side). Its output is browser-independent. It contains MathML in its output and the remaining of the output is correctly tagged to be ignored by readers:

    <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><msup><mi>g</mi><mi>a</mi></msup><mspace></mspace><mspace width="0.6666666666666666em"></mspace><mrow><mi mathvariant="normal">m</mi><mi mathvariant="normal">o</mi><mi mathvariant="normal">d</mi></mrow><mtext> </mtext><mtext> </mtext><mi>p</mi><mo>=</mo><mi>A</mi></mrow><annotation encoding="application/x-tex">g^a\mod p=A</annotation></semantics></math></span><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.858832em;vertical-align:-0.19444em;"></span><span class="mord"><span class="mord mathnormal" style="margin-right:0.03588em;">g</span><span class="msupsub"><span class="vlist-t"><span class="vlist-r"><span class="vlist" style="height:0.664392em;"><span style="top:-3.063em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mathnormal mtight">a</span></span></span></span></span></span></span></span><span class="mspace allowbreak"></span><span class="mspace" style="margin-right:0.6666666666666666em;"></span></span><span class="base"><span class="strut" style="height:0.8888799999999999em;vertical-align:-0.19444em;"></span><span class="mord"><span class="mord"><span class="mord mathrm">m</span><span class="mord mathrm">o</span><span class="mord mathrm">d</span></span></span><span class="mspace" style="margin-right:0.16666666666666666em;"></span><span class="mspace" style="margin-right:0.16666666666666666em;"></span><span class="mord mathnormal">p</span><span class="mspace" style="margin-right:0.2777777777777778em;"></span><span class="mrel">=</span><span class="mspace" style="margin-right:0.2777777777777778em;"></span></span><span class="base"><span class="strut" style="height:0.68333em;vertical-align:0em;"></span><span class="mord mathnormal">A</span></span></span></span>
This is:

    g^k\equiv a\pmod{p}


In my own experiments with mathematical writing, rendering KaTeX server-side increased the resulting HTML size by a nontrivial amount. I bet that if you took something small-textbook-sized, in terms of bytes it would be smaller to ship katex.js and get it to render the latex on the fly, rather than generating the HTML ahead of time.

Bit of a sad situation, but then again HTML and CSS is not really the best layout language for this kind of stuff.


JS on server-side can be taxing. If I don't use NodeJS, then I'd have to (1) call it from a script, eating the startup time (2) run a daemon of NodeJS workers running in parallel to my web server or (3) use an "embedded" JS engine, hoping I don't run into compatibility issues. All three options have performance costs + adds more dependencies.

If KaTeX were written in C, for example, it would be no problem FFI'ing it into just about any language. Plus whatever perf benefits there are of not using JS.


He wrote "can be generated". You can use KaTeX for setting up complete static web pages with no JS/server-side prozessing at all. Example from my blog:

https://depot.traits.de/pages/2020/02/21-markdown-example.ht...


For the vast majority of use cases, you should probably be pre-generating these anyways, and for the few use cases where content would be constantly changing, client-side rendering makes way more sense.


The thing specifically with KaTeX is that if you do this, you can blow page sizes out completely. In the example above, less than 20 characters of latex turned into a giant amount of HTML markup. Repeat this in many places for a mathematics-heavy page, and the browser might be better off just running KaTeX itself. Besides, you need to ship a whole bunch of fonts and a stylesheet anyway.


KaTeX has an 'output' option and one of his settings is 'mathml'. You can produce clean MathML this way and even mixed HTML/MathML output (default and what you see in the OP's example) with MathML for accessibility. Problem with the pure approach isn't KaTeX but the browser support.


Oh yeah, definitely, I was just responding to the "calling server-side JS" part. Even if the same library was implemented in native code, you still wouldn't want to be calling it inline from a cgi* script.


I think this might be what you're looking for: https://github.com/cqql/pelican-katex


I considered switching from MathJax to KaTeX for my MathJax-based projects such as https://github.com/susam/texme and http://mathb.in/ but I had to decide against doing so because MathJax supports commands like \begin{align}, \begin{equation}, \label, \eqref, \notag, etc. that KaTeX does not, so switching to KaTeX would break many existing documents written using TeXMe or MathBin. I am going to stick with MathJax for now.

Commands supported in MathJax: http://docs.mathjax.org/en/latest/input/tex/macros/

Commands supported in KaTeX: https://katex.org/docs/supported.html


For some reason in katex you have to use \begin{aligned} instead of \begin{align} but it works.


Yes, the "aligned" environment is a different environment but it is similar to the "align" environment. The "aligned" environment is available in MathJax too. The "aligned" environment is meant to be a part of a larger displayed math block, i.e., it goes between \[ and \] or $$ and $$. The "align" environment, on the other hand, is a standalone environment that can be used outside displayed math block.

While the "aligned" environment is supported by both MathJax and KaTeX, the "align" environment is supported by MathJax only.


Huh, I never knew that. Well in any case the differences are minor so you can just replace align with aligned

https://tex.stackexchange.com/questions/95402/what-is-the-di...


Isn't the big difference equation numbering? If you actually like to label and eqref stuff, it's not really a replacement. you can get around this I guess, but for me, it's much easier if my basic latex stuff works the same everywhere.


I don’t understand why the whole math related community have conditioned ourselves to tolerate the horrible *tex macro language universe and its tool chain for almost half a century.

Debugging is horrible, syntax is unnecessarily verbose, formatting is hit or miss, portability is pure lottery, compiling is suuuper slow.

When I write text in an editor, it just works. Why for math do I have to spend all of these additional computing cycles?

I don’t have an alternative (if I had I would have started a company), I just know that I hated all of the hours I wasted formatting math manuscripts and I wish somebody could stand up and go against Knuth’s way of thinking.


For people caring about typography there is nothing that reaches the output quality of TeX / LaTeX.

And that is not limited to math type setting, it holds for normal text.

Also, automatic tocs, I ist, bibliography with biblatex/biber.

Error messages are improving using modern packages.

The biggest problem ist the complete absence of dependency management. TeX distributions break regularly and the require workarounds because some package introduced a breaking change.


This is platform-dependent. On Windows, MikTeX is the standard way to work with LaTeX and it bundles a package manager for you.


It is because TeX provides the only acceptable output quality right now; also, TeX is like the C of math type setting. So whatever your improved solution is, it will have to include TeX at least partially, like MathJax or KaTeX.

It is what you get when you have a genius like Knuth taking math typesetting seriously. To get something better, you need somebody similar sitting down and take another serious stab at it.


Well, the complaint is mostly surface-level; I'm not sure if there's anything really stopping obe from treating tex as an engine/compile-target, and entirely changing the language that way

Afaik other *tex systems do it in the form of suites of tex macros, but no one really attempts to deviate from tex altogether


Adding to this, LaTeX is entirely incapable of producing even remotely accessible PDFs. If you're extremely lucky, you might be able to copy a single word or even multiple, but line breaks, inline equations and basically anything else breaks it entirely, which is not only incredibly annoying for citing things, but makes it entirely unusable for visually-impaired people.

Additionally, if equations are the the main appeal of it, how have we not made anything better? Why can't I plug the same code that renders my paper into a solver or convert it into Julia and run it? Like, properly, not just by guessing. I get that *tex is a typesetting language, but we're not typesetters!


If publishers provided the TeX source, you could do this.

I don't really see this as an issue. TeX is just a language that can be translated into PDFs for visual consumption well, but it could similarly be translated into audio or code (in the case of equations), we just can't do that because publishing TeX isn't something we do for some reason.


The problem is that you really can't. Tex isn't semantic, it's visual. Even matrix transposition, one of the most basic things in linear algebra, is written differently by different people. I've seen plenty of people just write ^T, which requires an amount of contextual awareness a parser just cannot have to differentiate from just raising something to the power of "T".


Mathematical notation is context-dependent and denser than code, you can't map directly from one to the other.


The main appeal isn't merely equations. The appeal is that it produces the best typesetting for prose and equations both.


Genuine question, what is the alternative in your view. All visual editors that I've ever used are much more cumbersome unless they take latex syntax.

Sure one could come up with some markup language that would have an easier syntax for relatively simple cases (see e.g. the post a bit further down), but to actually support the complex formulas that latex supports we would quickly end up with something very similar to latex.


I should clarify (I'm aware that you said you don't have an alternative). My question is of what type/form the alternative should take.


I think that a new paradigm should try to achieve the following: 1) Be based on code that can be machine interpreted and used afterwards in computations. Maybe this will require a more standardized way of writing math (like the apl that was suggested). 2) Be based on source code that is not cluttered and can be read easily by a human (maybe like markdown) 3) Most important of all: Formatting should be a completely independent layer. My original equations should have nothing more than math, it should be the renderer's business of how to present it to the consumer (webpage, pdf or whatever). It should be very easy for example to change the alignment of your equations a-posteriori without messing with the equations themselves.


1 feels too restrictive. I'm not sure how easily it would allow for writing math that isn't yet amenable to machine computation. Just as a random example, what if I'm doing some Étale cohomology stuff, maybe throw in some stacks and whatever else. How impressive would this code have to be?


We can have multiple "interpretation modules" and for some fields these will produce more useful output than for others. Currently, you cannot even attempt at doing so since the tex equations are typically polluted with formatting related code.


The problem is that mathematical notation itself is insanely complex and very nuanced, so any attempt to replicate it digitally will also be insanely complex.

A better solution IMO is an alternate mathematical notation which can be simple and unambiguous not only for humans, but also computers. Something like apl - https://www.jsoftware.com/papers/tot.htm


You should look into GNU TeXMacs [^0]. Its formulas (and document structure) are composed of S-Expressions that the user can edit directly. But it has a "TeX"-like UI (typing '\int' renders an integral symbol). Producing documents is an order of magnitude faster than LaTeX. And the quality is comparable.

[^0] https://www.texmacs.org/tmweb/home/welcome.en.html


What a terrible name! You have to read the documentation to discover the typesetting is not based on TeX, and the editor isn't Emacs.


The TeXmacs book is just out: https://www.scypress.com/book_info.html


Yes, it's a pain to write math related manuscripts.

Normal texts are a simple character list, so they are easy to input. Math equations are much more complex, with more symbols, 2D placement. So we need to 'mark up' the normal texts to provide enough information for a proper math equation.

Current machine learning can help translate hand-written equations into the one computer can understand, I think this can help a lot. However, if we want to use keyboard only, it still seems very hard to design a system that can input math as smooth as texts without 'mark up' or GUI.


I gave this problem a stab a few years ago. I wrote an ascii-math derived language (but more powerful, and a little easier) called MathUp. I planed for it to be quick to write and easy to read (kind of like markdown for math). However it is not nearly as powerful as latex (and I don’t plan for it to be). Target are people that are writing quick math-notes (e.g. in class), or on forums where participants don’t necessarily know latex but might need to write a non-trivial equation or two.

https://runarberg.github.io/mathup/


I agree that the LaTeX toolchain is bad, although there are some tools that make it better:

- latexmk knows how often it will need to compile a document in order to get all references right etc.

- pandoc lets you write markdown and converts it to LaTeX (although, if you have to write a lot if math you'll have to use LaTeX mode so often that it's worth considering whether that buys you anything... it's great for short, more textual documents that you want to format nicely though)

- XeTeX removes all the unicode and font problems and lets you actually include fonts on your system

- verbosity can be reduced somewhat by macros

But it's true. LaTeX kind of sucks (which is not really Knuth's "fault", since he only invented TeX and not LaTeX), the syntax errors can be very annoying (trying to hunt for that one missing paren or $...), packages constantly break other packages and totally absurd ways, and worst of all, the maths commands are entirely non-semantic (I've tried parsing maths expressions from LaTeX, it's not pretty), etc.

It's just that there is nothing better for maths right now, and even if there were, good luck fighting all the institutional inertia.


I don't really agree with you being downvoted; I love LaTeX, I use it for basically any kind of mathey stuff that I need, but it is an objectively irritating language, especially for beginners.

That said, the fact is that for mathematical equation editing, for better or worse, TeX-based systems have a near-monopoly on high-quality typesetting; KaTeX giving us a fast, easy-to-use implementation of it is still a net good.


There are plenty of alternatives. People don't use them.


If anyone cares, this works with screen readers.

The MathML output is there, and that's all screen readers need to render math properly.


I wish MathML was better supported :(


IIRC, chrome intentionally decided not to add support for MathML, but it looks like they may have changed their mind (https://www.chromestatus.com/feature/5240822173794304)?

Although, to be honest I'd rather have support for something closer to LaTeX. MathML is incredibly verbose, and certainly not something you would want to write by hand.


You should think of MathML like SVG. Most people use equation editors (a la Inkscape for SVGs) or a library (d3) that outputs MathML that you can include in your website. You also have the option to write simple equations by hand, but most people won’t.


The verbosity of MathML also has costs in terms of bandwidth (although that is mitigated by compression) and likely parsing speed.


Actually MathML is much simpler to parse: it's already parsed, what you get is basically an AST in XML.


That's a problem for mathml. The more required tooling, the less likely it is to be used. TeX hits this weird sweet spot between writing code and writing a document that's very productive.


Then use a library that converts TeX into MathML. I can recommend TeXZilla[1] (the author is also a major contributor to the MathML stadard).

    <p>
      The triangle inequality states that
      <la-tex>z \leq x + y</la-tex>.
    </p>
Disclosure: I am my self an author of an alternative library MathUp[2].

1: http://fred-wang.github.io/TeXZilla/

2: https://runarberg.github.io/mathup/


That still requires more tooling.


It is a little unfair since LaTeX has tons of extra libraries involved. It’s probably been more than 5 years since I touched LaTeX, but I usually (if I remember correctly) used amsmath, babel, biblatex, inputenc, fontenc, hyperref before I even started.

I don’t think it is unreasonable to ask authors that insist on writing in familiar syntax, that they use a tool that enables that. With native MathML authors are free to use whichever tool chain they prefer. Some authors will prefer graphical editing of equations, so they have their authoring tools set up that way. Others will just want to write their familiar latex syntax so they’ll put a:

    <script src="./path/to/texzilla.js"></script>
in their document and write as before.


Despite MathML being too verbose, if it were well supported across all major web browsers, we could write mathematical content in LaTeX or another syntax and then convert it to MathML. It would have been very similar to how a lot of content is written in Markdown these days and then converted to HTML.


An above post mentioned it is actually not google implementing it, but Igalia:

https://mathml.igalia.com/


looks like someone is sponsoring it:

https://mathml.igalia.com/


I switched from MathJax to Katex on my personal blog, and it significantly improved my lighthouse scores. Mathjax needs a huge amount of JS/CSS/Fonts to do its job, and takes a long time to load and render the equations. Not all of that is deferable.


I used Katex on my GatsbyJS blog and it worked nicely. Felt like doing latex but less confusing.


If you already know latex pretty well then it's pretty confusing because you'll keep finding that things you expect to work are not supported.


This is my experience as well. I just stick with MathJax for this reason. Since I'm already very familiar with LaTeX proper (use it every single work day), it's far less jarring to just use MathJax.


I was looking for a LaTeX rendering solution for a Flutter and ended up wrapping KaTeX: I use a platform-side web view to render with KaTeX and then send the rendered PNG bytes back to the Dart world.

https://pub.dev/packages/flutter_tex_js

It’s hacky but it’s been working incredibly well.



That package is incredibly immature. It couldn’t actually render almost anything the last time I tried it.


A big problem with systems like KaTeX and MathJAX is that they are not compatible with LaTeX. They are superficially similar, but not the same. LaTeX has a huge number of packages that serious math people heavily rely on.

What's needed is version of the underlying TeX engine that is HTML-aware. This way, a multipage document could be complied as usual, say to be printed or displayed as a static PDF, or it could be compiled to a web-friendly format for display in a browser, with links, etc.


MathJax is more complete than KaTeX and it is supported on GitHub Pages, see also https://g14n.info/2014/09/math-on-github-pages/


It's also a lot heavier and slower. Unless you need extra features that katex doesn't support it's best to use the latter.


It’s not “supported on GitHub Pages” in any specific way. Both engines can work client-side by scanning your HTML for LaTeX code enclosed in $$…$$ or \(…\) or other configurable delimiters. You can just drop the appropriate JS/CSS into your default layout, and you don’t need any special support from Jekyll for this to work. Kramdown can be configured with a math backend, and the only thing it will do in MathJax mode is replace $$…$ with \(…\) and \[…\] depending on the environment, and not parse escapes and Markdown syntax in that snippet. The KaTeX mode of kramdown does stuff server-side, which might not be desirable on GitHub Pages — but this is fixable by just telling Kramdown you’re using MathJax, and including KaTeX with auto-render in your templates.


We use this with markdown. Basically, we extended our markdown parser to parse anything between two $$ tags as KaTeX. It was really easy to implement. And, KaTeX is much faster than other alternatives we tested (Yes, that's what title says :) )


Have you encountered the situation where you need to include a $ symbol in your markdown yet? Very tricky and when the issue was raised with katex devs they basically said "not our problem" and closed it.


We actually use two $$ to start and end.

Ex: $$ c = \pm\sqrt{a^2 + b^2} $$

Or, multiline $$ \frac{1}{\Bigl(\sqrt{\phi \sqrt{5}}-\phi\Bigr) e^{\frac25 \pi}} = 1+\frac{e^{-2\pi}} {1+\frac{e^{-4\pi}} {1+\frac{e^{-6\pi}} {1+\frac{e^{-8\pi}} {1+\cdots} } } } $$

Some details are available [in this post](https://talk.hyvor.com/blog/introducing-katex-embed/) on how it works.

And, katex.renderToString has an option to set throwOnError: false.. So, whenever if the TeX code inside $$ is not valid, it just returns the text.


Yes, I do the same. I meant when you have to use a currency in dollars in your markdown. Try writing this sentence (sorry, it's early here and I can't think of a better example):

I have $3. $$\frac{3}{2}$$


Why not use &#36; ?


It's a while since I encountered this issue but I think the markdown engine was converting that back to $. In the end I had to use <span>$</span> and even that too some jumping through hoops because again markdown was removing html. This was in Hugo, whatever markdown engine they use.


For faster server-side rendering, this is a good, though relatively unknown resource:

https://github.com/cqql/pelican-katex


Still missing the ability to properly reference equations from text. e.g. `\refeq{}`.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: