Search code examples
javascriptmathkatex

How to box a formula in KaTex?


This question is similar to 6yrs old MathJax question; How to box a formula in MathJax?

How to achieve \boxed{...} with KaTex?

The intented output is as below;

enter image description here

KaTex code shows some amsmath translations in environments.js, but they are just 1:1 conversions from amsmath functions to existing KaTex expressions.

KaTex seems to utilize amsmath.sty but I don't know how to apply it.


Solution

  • I'm one of KaTeX's developers. We don't have boxes. Adding boxes around the whole equation shouldn't be too hard using some custom CSS. For example, you can take the KaTeX web page and type in your formula, c_i=\sum_jA_{ij}. Then you edit the CSS of that page (using web development tools in your browser or your own copy of this file) to add two more styles to the class .katex:

    .katex {
      border: 0.0625em solid currentcolor;
      padding: 0.5em;
    }
    

    Snapshot

    Now the formula is boxed. Using em as the unit of length for everything is consistent with KaTeX' other CSS, and doing so makes formulas scale as a whole no matter the font size of the surrounding text. If you only want to box some formulas, nest them inside some <div class="boxedmath"> and use that nesting as an additional CSS selector.

    It would be fairly easy to have some option to add additional classes to the top level <span class="katex">. If you think that would be useful, feel free to post a feature request or even a pull request with your own implementation.

    To have \boxed work within math mode would be harder. You'd essentially do something like above, but with a newly introduced class for the boxed part. You'd also need some code to compute the outer margins of the box based on those of the inner box, in such a way that the code exactly matches the CSS. And you should work out the padding and line width used by LaTeX, so that KaTeX matches that as closely as possible. This is where looking at the LaTeX implementation comes into play. Quite doable, but some work. Again worth a feature request or pull request if you think it useful.

    Doing this by strictly following amsmath.sty would be even harder. KaTeX still lacks many of the spacing primitives one would usually use for this, stretchable spaces in particular. I strongly suggest using a CSS-oriented implementation instead.

    To properly support this for all use cases, it would be nice to find the appropriate MathML rendering for boxes as well. While KaTeX doesn't use MathML to display the math, it still includes MathML for the sake of accessibility by screen readers and similar assistive technologies.