KaTeX: Add support for line breaks

Add support for line breaks. \\, \newline

Thanks.

About this issue

  • Original URL
  • State: closed
  • Created 10 years ago
  • Reactions: 59
  • Comments: 44 (14 by maintainers)

Most upvoted comments

@spelufo @spicyj @sohailykhan94 After an hour of experimentation, I’ve came out with a code injection / script hacking method which injects my code into the KaTeX context. This function automatically splits the line breaks with ease, and is friendly towards single-line equations.

This function ought have been used only once, before any render operations are executed.

hook: {
    katex_hook : null,
    katex : function() {
        // Store katex hook to local area
        hook.katex_hook = katex.render;
        // Destroy remote function
        katex.render = null;
        // Create desired hook function
        function remote_hook(rend_str, target, cfg) {
            rend_str = rend_str.replace('\n', ' ');
            rend_arr = rend_str.split('\\\\');
            if (rend_arr.length <= 1) {
                hook.katex_hook(rend_str, target, cfg);
            } else if (rend_arr.length > 1) {
                for (var i = 0; i < rend_arr.length; i++) {
                    rend_s = rend_arr[i];
                    elem = document.createElement('p');
                    hook.katex_hook(rend_s, elem, cfg);
                    target.appendChild(elem);
                }
            }
            return ;
        }
        // Join to global function
        katex.render = remote_hook;
        // Succeeded
        return true;
    }
}
hook.katex();

You may also use this one with some additional CSS tweaks, which are extremely useful in responsive designs. Inline equations wraps at the end of the line, and displayed equations scroll when being too long. Stick these code into the CSS stylesheet.

span.math.display {
  display: inline-block;
  max-width: 100%;
  overflow-x: scroll;
}
.katex-display > .katex {
  display: inline-block;
  white-space: nowrap;
  text-align: initial;
}
.katex {
  font: normal 1.21em KaTeX_Main, Times New Roman, serif;
  line-height: 1.2;
  white-space: normal;
  text-indent: 0;
}

Hope this may help you do this. However, display effects might differ from TeX standards, and this is only a quick fix. May these tweaks be incorporated into the master branch, and leave a thumbs up if you find this useful.


5 April fix: The CSS works bad on desktops. Now it looks better for .katex .display.

span.math.display {
  display: inline-block;
  width: 100%;
  overflow-x: auto;
}

I’m new to this thread. Neat hack!

In terms of workarounds, it seems that adding \begin{aligned} ... \end{aligned} around your multi-line text would also be good. OK, to get left justification of each line, you have to add & to the beginning of each line too. But this input looks pretty good on the KaTeX tester:

\begin{aligned}
&p_1 = some\ point, \\
&p_2 = some\ other\ point, \\
&distance = (p_2 - p_1), \\
&ratio = \frac{percentage}{100}, \\
&new\ point = p_1 + distance \cdot ratio
\end{aligned}

example

I was surprised to learn that \\ and \newline work in math mode in LaTeX. Note, however, that they do not work in display environments ($$...$$ and \[...\]) – or rather, they compile, but don’t break the line. (Their definition must be overridden by those environments.) They do work in $\displaystyle ...$ though.

Anyway, it seems that the way to implement this would be to somehow transform line1 \\ line2 into the equivalent of \begin{aligned} &line1 \\ &line2 \end{aligned}. I think this could be done via the infix operator mechanism in Parser.js… though I’m not quite sure how it would work with multiple \\s.

This is how I’m dealing with it in my react project:

function MathDisplay ({ ...props }) {
	var returnVal;
	var text = { ...props }.data;
	var arr = text.split('\\\\');
	for (var i = 0; i < arr.length; i++) {
		var math = katex.renderToString(arr[i], { throwOnError: false, errorColor: '#FF0033' });
		if (typeof returnVal === "undefined") {
			returnVal = '<p>' + math + '</p>';
		} else {
			returnVal = returnVal + '<p>' + math + '</p>';
		}
	}
	return (<div dangerouslySetInnerHTML={{ __html: returnVal }} />);
};

Its a hack and I feel very dirty, but deadline soon. Might help someone else.

@tivewsalaeharad Please open a new issue, and include an example of the LaTeX code you’re expecting to wrap that isn’t (maybe with a screenshot).

PR #1298 implements \\ and \newline at the top level of inline math.

Some documentation on how to set up MathJax as a fallback for KaTeX in the mean time would probably be good.

@anirudha-banerjee Yes, KA uses MathJax when KaTeX fails.

OK, good to know there’s applications. I’m interested in working at this at some point, but don’t know when I’ll have time.