Add support for line breaks. \\, \newline...
Thanks.
That one would be very nice indeed. Or eqnarray.
+1
:+1: Would be great.
Any update on this, guys?
Can you all give some examples of how you would use it? Would you want it in the context of some matrix-like environment like \begin{array} or \begin{align} or somewhere else?
In my case I'd like to generate two equations with one string:
Eq1 = 1.23 * 5^5 * 5.3 \newline
Eq2 = 3.21 * 2^2 * 3.5
Also of note, supporting empty spaces would be useful. In Latex, I'd use something like:
\hspace{2}
Yes @spicyj, the idea was to align several equations, like one would do with {eqnarray}, for example.
We're close to adding support for \begin{align*}, which should satisfy these needs.
@xymostech any updates on this?
Are there any plans to add support for \hspace{2px} ?
I need this to format numbers, meaning I have things like:
12\hspace{2px}345
@scaljeri It seems like \hspace would be relatively easy to implement. It would probably have more success as a separate issue.
@octatoan support for \begin{align*} is in code review, but the current implement doesn't behave well with infix operators such as \over. It's going to take some time to resolve this issue.
+1 for \\ and \newline.
<p class="tex">x + 4 = 6</p>
<p class="tex">x = 2</p>
is just too much and would require extra CSS to bring the two paragraphs closer together. The following, on the other hand, would be perfect:
<p class="tex">x + 4 = 6\\x = 2</p>
:+1:
In the absence of a simple "Vote!" button: /me wants! :+1:
:+1:
Newline useful for showing derivations or other calculations that take more than one line to solve...
Not sure if there's a more elegant way to do it, but currently this is what my html looks like,
<div id="line1"></div>
<div id="line2"></div>
<div id="line3"></div>
<div id="line4"></div>
<script>
katex.render("a = \\frac{V_{2} - V_1}{t}; \\quad V_{2y}=0", $("#line1")[0] );
katex.render("t = \\frac{-V_{1y}}{a_{y}}", $("#line2")[0] );
katex.render("t = \\frac{-V_{1y}}{-9.81\\ {m s^{-2}}}", $("#line3")[0] );
katex.render("t = \\frac{V_{1y}}{9.81\\ {m s^{-2}}}", $("#line4")[0] );
</script>
Not very pretty.
We're hoping to have align* support sometime soon, and then you would be able to line up the equals signs as well.
Ah, I see. Cool!
:+1:
The \\ notation is also supported in plain math mode, so that even without an align environment, the following compiles as expected in LaTeX:
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
This currently causes KaTeX to error out, so adding in support for this is pretty important for some (in my case, https://pomax.github.io/bezierinfo, "A Primer on Bezier curves", uses it in a fair few places, and I would love to be able to finally leave MathJax for KaTeX)
Any update on this?
@kirbyfan64 the new release includes the aligned environment... other than that, no update.
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.
I now generate SVG during bundling (with images named based on a hash of the LaTeX code that they represent, and with the original LaTeX code added as comments) so that there is no need for dangerouslySetInnerHTML anymore, so I also don't have to worry about the client's processing capabilities anymore. That's not a solution for everyone, but it's a solution with many benefits for users, and makes it easier to deal with "can I use KaTeX or do I need to fall back to MathJax".
This lack of function had caused my site to fail on numerous occasions after migrating MathJax to KaTeX.
I'm currently waiting for a solution (and not a hack... :P) to get this working. I suggest that this linebreak should be added to the release ASAP, regardless whether it would break some visual workarounds, lest it should break a number of sites which highly rely on \\ or \newline.
@sohailykhan94 probably you could make a code injection (a.k.a. hook) into the KaTeX class so it could temporarily render line breaks?
Edit: I've written a code injection method available below.
@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}

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.
You might be surprised again, @edemaine: I feed the following LaTeX source for typesetting to XeLaTeX, which happily compiles it with line breaks inside \[...\]:
\documentclass[12pt]{article}
\usepackage[paperwidth=12in, paperheight=12in]{geometry}
\pagestyle{empty}
\usepackage{color}
\usepackage{amsmath}
\usepackage{unicode-math}
\setmainfont[Ligatures=TeX]{TeX Gyre Pagella}
\setmathfont{TeX Gyre Pagella Math}
\begin{document}
\[
Given \left (
\begin{aligned}
p_1 &= some\ point \\
p_2 &= some\ other\ point \\
distance &= (p_2 - p_1) \\
ratio &= \frac{percentage}{100} \\
\end{aligned}
\right ),\ our\ new\ point = p_1 + distance \cdot ratio
\]
\end{document}
This results in:
(after running it through pdfcrop because that's obviously not a 12"x12" image =)
Yes, of course \\ works inside {aligned} -- that's how that environment is supposed to work. It works perfectly in KaTeX too! What surprised me is that \\ works outside any sort of array/tabular environment, (but not in \[...\]).
Ah, my mistake, misread what you'd said. \\ is kind of magical in that as a fully user controlled macro that each package is basically free to do with whatever they like and reading through http://tex.stackexchange.com/a/225925/8406 it sounds like it'll "do a thing" in any environment that doesn't redeclare what \\ is supposed to mean. Given the default meaning in LaTeX of \hskip\break, I guess it'll "work" in any environment where \hskip\break are legal instructions, plus any environment that redefined \\ itself to do something subtly different under the bonnet but with the same visual effect.
...now I'm curious if anyone has a list that notes which enviroments do what for \\ (google is not yielding one but then it's notoriously bad at finding "explanations" around (La)TeX's working, prefering to hand you a million tutorials for the env/cmd in question instead)
Is there any update on this?
I mean can i use \\ outside {aligned}, in v0.9.0-alpha1
If not, is there any alternative to \\, which can be used outside {aligned}?
@anirudha-banerjee No, this hasn't been worked on yet. (You're certainly welcome to try yourself!)
Is there a reason you don't want to use aligned? There is another new environment in progress called alignedat but I'm not sure it will be any different for your application.
@edemaine Thank you for the response.
My application is content heavy, so there are lots of formulae and symbols. Now, previously i was using mathjax and that supports \\ outside {aligned}. So, all my content has \\ outside {aligned}, and katex doesn't render those formulae.
Now, the thing is, there are lots of formulae and editing each one and adding \begin{aligned} ..... \end{aligned} will become a real pain. So, please can you check, if there is any alternative to this, because that would be really helpful.
Khan Academy has content with \\ outside {aligned} as well.
i have tried putting \\ without \begin{aligned} and \end{aligned}, but it throws error.
Error: KaTeX parse error: Expected 'EOF', got '\\' at position 11: \boxed{A} \滩\滩 \boxed{b}
only works if i write this inside \begin{aligned} ...... \end{aligned}
@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.
Sorry I should've mentioned that KA uses MathJax as a fallback. It's something we'd like to get away from and thus very much interested in support \\ outside of {aligned}.
@edemaine @kevinbarabash Thank you for your quick replies. I guess i'll also follow this option then, the MathJax as a failsafe one.
Some documentation on how to set up MathJax as a fallback for KaTeX in the mean time would probably be good.
PR #1298 implements \\ and \newline at the top level of inline math.
@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; }
Dear Mr. Jeffswt, sorry, but I'm not skillful at JavaScript. Could you explain in details, where to paste this fragment for to provide automatical word wrap of formulae?
@tivewsalaeharad This issue is closed. Clean solutions for this issue have been incorporated to the latest version through PR #1298. So the JS snippet above is no longer required.
And no. Formulae should auto wrap (I recall) by default and the CSS tweak is supposed to disable auto word wrapping.
As for embedding a JavaScript, you just put the snippet at the end of the HTML document, enclosed with a pair of <script> tags. That should work. (Ask Google and try it yourself before posting in the issues section. Project maintainers are receiving too many Emails.)
@tivewsalaeharad This issue is closed. _Clean_ solutions for this issue have been incorporated to the latest version through PR #1298. So the JS snippet above is no longer required.
And no. Formulae should auto wrap (I recall) by default and the CSS tweak is supposed to disable auto word wrapping.
As for embedding a JavaScript, you just put the snippet at the end of the HTML document, enclosed with a pair of
<script>tags. That should work. (Ask Google and try it yourself before posting in the issues section. Project maintainers are receiving too many Emails.)
I have KaTeX v0.10.0
My code (in Android Studio):
WebView webView = new WebView(SpaceActivity.this);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
webView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
webView.setPadding(2, valueViewer.getTextPadding(), 2, valueViewer.getTextPadding());
String html = "<!DOCTYPE html>\n" +
"<html>\n" +
" <head>\n" +
" <meta charset=\"UTF-8\">\n" +
" <title>Auto-render test</title>\n" +
" <link rel=\"stylesheet\" type=\"text/css\" href=\"file:///android_asset/katex/katex.min.css\">\n" +
" <script type=\"text/javascript\" src=\"file:///android_asset/katex/katex.min.js\"></script>\n" +
" <script type=\"text/javascript\" src=\"file:///android_asset/katex/contrib/auto-render.min.js\"></script>\n" +
" </head>\n" +
" <body>\n" +
" " + expression + // variable, containing formula in TeX-format
" <script>\n" +
" renderMathInElement(\n" +
" document.body\n" +
" );\n" +
" </script>\n" +
" </body>\n" +
"</html>";
webView.getSettings().setSupportZoom(true);
webView.loadDataWithBaseURL("file:///android_asset/", html, "text/html", "utf-8", null);
And no word wrap :-( I have been searching Google for 8 hours yesterday, but haven't seen the solution
@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).
is there anyway for line breaking within a cell in array? \newline seems doesn't work
Most helpful comment
@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.
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.
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.