<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="icon" type="image/png" href="favicon.png">
<title></title>
<meta name="description" content="" />
<link href="style.css" rel="stylesheet" type="text/css" />
<style>
div {
padding: 1rem;
}
</style>
</head>
<body>
<div>
Input String: <input type="text" style="width: 20rem;" value="3+\lim_{x\to \infty} f(x) = \sum_{i=0}^{10} g(x) = \prod h(x)" oninput="outputEl.textContent = latexReplaceSpaces(this.value);" onchange="outputEl.textContent = latexReplaceSpaces(this.value);" />
</div>
<div>
Output: <span id="output"></span>
</div>
<div>
Enter a string in the input above and some common integral LaTeX syntax will be parsed.
</div>
<script src="script.js"></script>
<script>
var outputEl = document.getElementById('output');
</script>
</body>
</html>
function nextSpaces(input) {
var openPar = 0;
var firstSpace = 0;
for (var i=0;i<input.length;i++){
if (input[i] == "(" || input[i] == "{" || input[i] == "["){
openPar++;
}
else if (input[i] == ")" || input[i] == "}" || input[i] == "]"){
openPar--;
}
if (openPar == 0){
if (firstSpace == 1){
if (input[i] != " " && input[i] != "\t" && input[i] != "\n"){
firstSpace = -1;
input=input.substring(0,i-1)+"{"+input.substring(i);
}
continue;
}
if (input[i] == " " || input[i] == "\t" || input[i] == "\n"){
if (firstSpace == 0){
firstSpace = 1;
}
else {
input=input.substring(0,i)+"}"+input.substring(i+1);
break;
}
}
}
else if (openPar < 0){
if (firstSpace == -1){
input=input.substring(0,i)+"}"+input.substring(i);
break;
}
}
if (firstSpace == -1 && i == input.length - 1){
input += "}";
break;
}
}
return input;
}
function latexReplaceSpaces(input){
for (var i=0;i<input.length;i++){
if (input[i] == "m"){
if (i >= 3 && input.substring(i-3,i+1) == "\\lim"){
input = input.substring(0,i)+nextSpaces(input.substring(i));
}
else if (i >= 3 && input.substring(i-3,i+1) == "\\sum"){
input = input.substring(0,i)+nextSpaces(input.substring(i));
}
else if (i >= 6 && input.substring(i-6,i+1) == "\\mathrm"){
input = input.substring(0,i)+nextSpaces(input.substring(i));
}
}
else if (input[i] == "d"){
if (i >= 4 && input.substring(i-4,i+1) == "\\prod"){
input = input.substring(0,i)+nextSpaces(input.substring(i));
}
}
}
return input;
}
About
This repl handles a few scenarios where whitespace plays an important role in LaTeX parsing.
To view this on TripleLog, click here.
HTML
The HTML is a simple input/output to change a string of text.
CSS
Add CSS by editing the style.css file that is linked to in the head section or inline edit the style section in the head.
JavaScript
The script.js file looks for \lim, \sum, and \prod and replaces upcoming whitespace with {} to keep the expression properly grouped for later parsing