All files parser.js

95.85% Statements 370/386
95% Branches 247/260
96.88% Functions 31/32
96.09% Lines 344/358

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 72815x 15x     317x 1816x         1816x 1522x     294x 498x     294x       15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x       263x 263x     263x 263x 263x     789x 554x 554x 554x   554x 5183x 5183x 5183x 162x 100x 100x   5021x 347x 4674x 344x       554x   554x       3099x 2004x 587x     1417x     384x         384x 384x   384x   16x   16x     368x     1033x         1033x       44x 44x     1033x         328x 4x   324x   324x                     1344x 15x           1329x 1329x 1329x   1329x     16x   16x 16x 1313x 6x 6x 6x 6x   6x 6x 1307x 5x 5x 5x 5x   5x       5x 1302x     10x 5x 5x 5x   5x 5x   1292x     16x 16x 16x 16x   16x     13x   4x       4x 9x 9x       9x   13x   2x 2x 2x 2x   1x 1x 1x 1x       1276x     47x   47x       47x 1229x     8x 8x 8x   8x 8x 1221x       176x       176x 176x 176x 176x     176x         20x   1x     20x 20x         20x 156x     18x   18x   2x     18x 61x     18x       138x 138x 138x   138x 3x   138x   1045x       87x   87x 87x 958x     218x   218x 218x 740x     8x 8x 8x 732x     627x     209x 209x 209x 209x 209x 209x 209x 6x 6x   209x 7x   209x 3x   209x 3x 3x     209x 209x 523x   98x     98x     98x 98x 425x     1x 1x   424x 424x     1329x 221x       35x   35x 186x       6x   6x 180x       40x   40x 140x       10x   10x       1329x       35x               35x   35x     35x       8x 8x             8x 8x 8x 8x   27x 27x     35x       40x               40x   40x     40x     4x 4x             4x 4x 4x 4x   36x 36x     40x       6x               6x   6x     6x 6x                       6x     6x       10x               10x   10x     10x 10x 1x             1x 1x 1x   9x     10x       45x 45x       45x 8x 8x 8x 37x 37x   45x   45x         45x       1x   44x       99x 99x 99x 99x 99x   99x 99x   99x 12x 12x 12x 87x           99x       20x 20x 20x 42x   42x     288x 138x 42x     96x 96x     354x 214x 42x   172x 54x     118x 118x     263x             229x 229x   229x       229x     229x 229x               557x 557x 3x 3x       3x     554x   554x 554x 554x 11909x 609x 554x   55x   11355x 55x       554x       5x 5x   5x 3x 2x 2x     5x 5x 5x 21x 21x 21x 6x 6x 5x   15x 6x     5x       209x       418x       31x     15x   15x  
import syntax from "./syntax";
import { numbers, identifiers, operators, groupings, accents } from "./lexicon";
 
function tag(tagname) {
  return function fn(content, attr) {
    Iif (typeof content === "object") {
      // Curry
      return str => fn(str, content);
    }
 
    if (typeof attr !== "object") {
      return `<${tagname}>${content}</${tagname}>`;
    }
 
    const attrstr = Object.keys(attr)
      .map(key => `${key}="${attr[key]}"`)
      .join(" ");
 
    return `<${tagname} ${attrstr}>${content}</${tagname}>`;
  };
}
 
const mi = tag("mi");
const mn = tag("mn");
const mo = tag("mo");
const mfrac = tag("mfrac");
const msup = tag("msup");
const msub = tag("msub");
const msubsup = tag("msubsup");
const munder = tag("munder");
const mover = tag("mover");
const munderover = tag("munderover");
const menclose = tag("menclose");
const mrow = tag("mrow");
const msqrt = tag("msqrt");
const mroot = tag("mroot");
const mfenced = tag("mfenced");
const mtable = tag("mtable");
const mtr = tag("mtr");
const mtd = tag("mtd");
 
function parser(options) {
  const decimalMarkRE =
    options.decimalMark === "." ? "\\." : options.decimalMark;
  const numberRegexp = new RegExp(
    `^${numbers.digitRange}+(${decimalMarkRE}${numbers.digitRange}+)?`
  );
  const colsplit = splitby(options.colSep);
  const rowsplit = splitby(options.rowSep);
  const newlinesplit = splitby("\n");
 
  function splitby(sep) {
    return str => {
      const split = [];
      let inners = 0;
      let index = 0;
 
      for (let i = 0; i < str.length; i += 1) {
        const rest = str.slice(i);
        const char = str[i];
        if (rest.startsWith(sep) && !str.slice(0, i).match(/\\(\\{2})*$/)) {
          if (inners === 0) {
            split.push(str.slice(index, i));
            index = i + sep.length;
          }
        } else if (char.match(groupings.open.regexp)) {
          inners += 1;
        } else if (char.match(groupings.close.regexp)) {
          inners -= 1;
        }
      }
 
      split.push(str.slice(index));
 
      return split;
    };
  }
 
  const parse = function parse(ascii, mathml, space, grouped) {
    if (!ascii) {
      return mathml;
    }
 
    if (ascii.match(/^\s/)) {
      // Dont include the space it if there is a binary infix becoming
      // a prefix
      Iif (ascii.match(/^\s+(\/[^/]|^[^^]|_[^_|])/)) {
        return parse(ascii.trim(), mathml, true);
      }
 
      // Count the number of leading spaces
      const spaces = ascii.match(/^ +/);
      const spacecount = spaces ? spaces[0].length : 0;
 
      if (spacecount > 1) {
        // spacewidth is a linear function of spacecount
        const spaceel = `<mspace width="${spacecount - 1}ex" />`;
 
        return parse(ascii.trim(), mathml + spaceel, true);
      }
 
      return parse(ascii.trim(), mathml, true);
    }
 
    let [el, rest] = parseone(ascii, grouped);
 
    // ## Binary infixes ##
 
    // ### Fraction ###
    if (
      ((rest && rest.trimLeft().startsWith("/")) ||
        rest.trimLeft().startsWith("./")) &&
      !rest.trimLeft().match(/^\.?\/\//)
    ) {
      [el, rest] = splitNextFraction(el, rest);
    }
 
    return parse(rest, mathml + el, false);
  };
 
  function parsegroup(ascii) {
    // Takes one asciiMath string and returns mathml in one group
    if (ascii.trim().length === 0) {
      return "";
    }
    const mathml = parse(ascii, "", false, true);
 
    return mathml === getlastel(mathml) ? mathml : mrow(mathml);
  }
 
  function parseone(ascii, grouped, lastel) {
    /**
     Return a split of the first element parsed to MathML and the rest
     of the string unparsed.
     */
 
    // TODO: split this up into smaller more readable code
 
    if (!ascii) {
      return ["", ""];
    }
 
    let el;
    let rest;
 
    const head = ascii[0];
    const tail = ascii.slice(1);
    const nextsymbol = head + (tail.match(/^[A-Za-z]+/) || "");
 
    if (ascii.startsWith("sqrt")) {
      // ## Roots ##
 
      const split = parseone(ascii.slice(4).trim(), grouped);
 
      el = msqrt(split[0] ? removeSurroundingBrackets(split[0]) : mrow(""));
      [, rest] = split;
    } else if (ascii.startsWith("root")) {
      const one = parseone(ascii.slice(4).trimLeft(), grouped);
      const index = one[0] ? removeSurroundingBrackets(one[0]) : mrow("");
      const two = parseone(one[1].trimLeft(), grouped);
      const base = two[0] ? removeSurroundingBrackets(two[0]) : mrow("");
 
      el = mroot(base + index);
      [, rest] = two;
    } else if (ascii.startsWith("binom")) {
      const [, , group, , after] = syntax.splitNextGroup(ascii);
      const [a, b] = colsplit(group);
      const over = parsegroup(a.trim()) || mrow("");
      const under = parsegroup(b.trim()) || mrow("");
 
      el = mfenced(mfrac(over + under, { linethickness: 0 }), {
        open: "(",
        close: ")"
      });
      rest = after;
    } else if (head === "\\" && ascii.length > 1) {
      // ## Forced opperator ##
 
      if (ascii[1].match(/[([]/)) {
        const stop = findmatching(tail);
        el = mo(ascii.slice(2, stop));
        rest = ascii.slice(stop + 1);
      } else {
        el = mo(ascii[1]);
        rest = ascii.slice(2);
      }
    } else if (accents.contains(nextsymbol)) {
      // ## Accents ##
 
      const accent = accents.get(nextsymbol);
      const next = ascii.slice(nextsymbol.length).trimLeft();
      const ijmatch = next.match(/^\s*\(?([ij])\)?/);
      const split = parseone(next);
 
      switch (accent.type) {
        // ## Accents on top ##
        case "over":
          if (ijmatch) {
            // use non-dotted i and j glyphs as to not clutter
            el = mover(
              mi(ijmatch[1] === "i" ? "ı" : "ȷ") +
                mo(accent.accent, { accent: true })
            );
            rest = next.slice(ijmatch[0].length);
          } else {
            el = mover(
              removeSurroundingBrackets(split[0]) +
                mo(accent.accent, { accent: true })
            );
            [, rest] = split;
          }
          break;
        // ## Accents below ##
        case "under":
          el = munder(removeSurroundingBrackets(split[0]) + mo(accent.accent));
          [, rest] = split;
          break;
        // ## Enclosings
        case "enclose":
          el = menclose(removeSurroundingBrackets(split[0]), accent.attrs);
          [, rest] = split;
          break;
        default:
          throw new Error(`Invalid config for accent ${nextsymbol}`);
      }
    } else if (syntax.isfontCommand(ascii)) {
      // ## Font Commands ##
 
      const split = syntax.splitfont(ascii);
 
      el = tag(split.tagname)(
        split.text,
        split.font && { mathvariant: split.font }
      );
      rest = split.rest;
    } else if (groupings.complex.contains(nextsymbol)) {
      // ## Complex groupings ##
 
      const grouping = groupings.complex.get(nextsymbol);
      const next = ascii.slice(nextsymbol.length).trimLeft();
      const split = parseone(next);
 
      el = mfenced(removeSurroundingBrackets(split[0]), grouping);
      [, rest] = split;
    } else if (syntax.isgroupStart(ascii) || syntax.isvertGroupStart(ascii)) {
      // ## Groupings ##
 
      // eslint-disable-next-line prefer-const
      let [, open, group, close, after] = syntax.isgroupStart(ascii)
        ? syntax.splitNextGroup(ascii)
        : syntax.splitNextVert(ascii);
 
      rest = groupings.open.get(after);
      const rows = (() => {
        const lines = newlinesplit(group);
        return lines.length > 1 ? lines : rowsplit(group);
      })();
 
      if (
        syntax.ismatrixInterior(group.trim(), options.colSep, options.rowSep)
      ) {
        // ### Matrix ##
 
        if (group.trim().endsWith(options.colSep)) {
          // trailing row break
          group = group.trimRight().slice(0, -1);
        }
 
        const cases = open === "{" && close === "";
        const table = parsetable(
          group,
          cases && { columnalign: "center left" }
        );
 
        el = mfenced(table, { open, close });
      } else if (rows.length > 1) {
        // ### Column vector ###
 
        let vector = rows.map(colsplit);
 
        if (last(vector).length === 1 && last(vector)[0].match(/^\s*$/)) {
          // A trailing rowbreak
          vector = vector.slice(0, -1);
        }
 
        const matrix = vector
          .map(row => mtr(row.map(x => mtd(parsegroup(x))).join("")))
          .join("");
 
        el = mfenced(mtable(matrix), { open, close });
      } else {
        // ### A fenced group ###
 
        const cols = colsplit(group);
        const els = cols.map(parsegroup).join("");
        const attrs = { open, close };
 
        if (options.colSep !== ",") {
          attrs.separators = options.colSep;
        }
        el = mfenced(els, attrs);
      }
    } else if (!grouped && syntax.isgroupable(ascii, options)) {
      // ## Whitespace ##
 
      // treat whitespace separated subexpressions as a group
      const split = splitNextWhitespace(ascii);
 
      el = parsegroup(split[0]);
      [, rest] = split;
    } else if (numbers.isdigit(head)) {
      // ## Number ##
 
      const number = ascii.match(numberRegexp)[0];
 
      el = mn(number);
      rest = tail.slice(number.length - 1);
    } else if (ascii.match(/^#`[^`]+`/)) {
      // ## Forced number ##
 
      const number = ascii.match(/^#`([^`]+)`/)[1];
      el = mn(number);
      rest = ascii.slice(number.length + 3);
    } else if (
      ascii.match(new RegExp(`^${operators.regexp.source}`)) &&
      !identifiers.contains(nextsymbol)
    ) {
      // ## Operators ##
 
      const [op, next] = syntax.splitNextOperator(ascii);
      const derivative = ascii.startsWith("'");
      const prefix = contains(["∂", "∇"], op);
      const stretchy = contains(["|"], op);
      const mid = ascii.startsWith("| ");
      const attr = {};
      if (derivative) {
        attr.lspace = 0;
        attr.rspace = 0;
      }
      if (prefix) {
        attr.rspace = 0;
      }
      if (stretchy) {
        attr.stretchy = true;
      }
      if (mid) {
        attr.lspace = "veryverythickmathspace";
        attr.rspace = "veryverythickmathspace";
      }
 
      el = mo(op, !isempty(attr) && attr);
      rest = next;
    } else if (identifiers.contains(nextsymbol)) {
      // Perhaps a special identifier character
      const ident = identifiers[nextsymbol];
 
      // Uppercase greeks are roman font variant
      const uppercase = ident.match(
        /[\u0391-\u03A9\u2100-\u214F\u2200-\u22FF]/
      );
      el = uppercase ? mi(ident, { mathvariant: "normal" }) : mi(ident);
      rest = tail.slice(nextsymbol.length - 1);
    } else if (head === "O" && tail[0] === "/") {
      // The special case of the empty set. I suppose there is no
      // dividing by the latin capital letter O
      el = mi(identifiers["O/"], { mathvariant: "normal" });
      rest = tail.slice(1);
    } else {
      el = mi(head);
      rest = tail;
    }
 
    if (rest && rest.trimLeft().match(/\.?[\^_]/)) {
      if (
        (lastel ? !lastel.match(/m(sup|over)/) : true) &&
        rest.trim().startsWith("_") &&
        (rest.trim().length <= 1 || !rest.trim()[1].match(/[|_]/))
      ) {
        // ### Subscript ###
        [el, rest] = splitNextSubscript(el, rest);
      } else if (
        lastel !== "mover" &&
        rest.trim().startsWith("._") &&
        (rest.trim().length <= 2 || !rest.trim()[2].match(/[|_]/))
      ) {
        // ### Underscript ###
        [el, rest] = splitNextUnderscript(el, rest);
      } else if (
        (lastel ? !lastel.match(/m(sub|under)/) : true) &&
        rest.trim().startsWith("^") &&
        (rest.trim().length <= 1 || rest.trim()[1] !== "^")
      ) {
        // ### Superscript ###
        [el, rest] = splitNextSuperscript(el, rest);
      } else if (
        lastel !== "munder" &&
        rest.trim().startsWith(".^") &&
        (rest.trim().length <= 2 || rest.trim()[2] !== "^")
      ) {
        // ### Overscript ###
        [el, rest] = splitNextOverscript(el, rest);
      }
    }
 
    return [el, rest];
  }
 
  function splitNextSubscript(el, rest) {
    const next = parseone(
      rest
        .trim()
        .slice(1)
        .trim(),
      true,
      "msub"
    );
    const sub = next[0] ? removeSurroundingBrackets(next[0]) : mrow("");
    let ml;
    let ascii = next[1];
 
    // ### Supersubscript ###
    if (
      ascii &&
      ascii.trim().startsWith("^") &&
      (ascii.trim().length <= 1 || !ascii.trim()[1] !== "^")
    ) {
      const next2 = parseone(
        ascii
          .trim()
          .slice(1)
          .trim(),
        true
      );
      const sup = next2[0] ? removeSurroundingBrackets(next2[0]) : mrow("");
      const tagfun = syntax.shouldGoUnder(el) ? munderover : msubsup;
      ml = tagfun(el + sub + sup);
      [, ascii] = next2;
    } else {
      const tagfun = syntax.shouldGoUnder(el) ? munder : msub;
      ml = tagfun(el + sub);
    }
 
    return [ml, ascii];
  }
 
  function splitNextSuperscript(el, rest) {
    const next = parseone(
      rest
        .trim()
        .slice(1)
        .trim(),
      true,
      "msup"
    );
    const sup = next[0] ? removeSurroundingBrackets(next[0]) : mrow("");
    let ml;
    let ascii = next[1];
 
    // ### Super- subscript ###
    if (
      ascii.trim().startsWith("_") &&
      (ascii.trim().length <= 1 || !ascii.trim()[1].match(/[|_]/))
    ) {
      const next2 = parseone(
        ascii
          .trim()
          .slice(1)
          .trim(),
        true
      );
      const sub = next2[0] ? removeSurroundingBrackets(next2[0]) : mrow("");
      const tagfun = syntax.shouldGoUnder(el) ? munderover : msubsup;
      ml = tagfun(el + sub + sup);
      [, ascii] = next2;
    } else {
      const tagfun = syntax.shouldGoUnder(el) ? mover : msup;
      ml = tagfun(el + sup);
    }
 
    return [ml, ascii];
  }
 
  function splitNextUnderscript(el, rest) {
    const next = parseone(
      rest
        .trim()
        .slice(2)
        .trim(),
      true,
      "munder"
    );
    const under = next[0] ? removeSurroundingBrackets(next[0]) : mrow("");
    let ml;
    let ascii = next[1];
 
    // ### Under- overscript ###
    const overmatch = ascii.match(/^(\.?\^)[^^]/);
    Iif (overmatch) {
      const next2 = parseone(
        ascii
          .trim()
          .slice(overmatch[1].length)
          .trim(),
        true
      );
      const over = next2[0] ? removeSurroundingBrackets(next2[0]) : mrow("");
      ml = munderover(el + under + over);
      [, ascii] = next2;
    } else {
      ml = munder(el + under);
    }
 
    return [ml, ascii];
  }
 
  function splitNextOverscript(el, rest) {
    const next = parseone(
      rest
        .trim()
        .slice(2)
        .trim(),
      true,
      "mover"
    );
    const over = next[0] ? removeSurroundingBrackets(next[0]) : mrow("");
    let ml;
    let ascii = next[1];
 
    // ### Under- overscript ###
    const undermatch = ascii.match(/^(\.?_)[^_|]/);
    if (undermatch) {
      const next2 = parseone(
        ascii
          .trim()
          .slice(undermatch[1].length)
          .trim(),
        true
      );
      const under = next2[0] ? removeSurroundingBrackets(next2[0]) : mrow("");
      ml = munderover(el + under + over);
      [, ascii] = next2;
    } else {
      ml = mover(el + over);
    }
 
    return [ml, ascii];
  }
 
  function splitNextFraction(el, rest) {
    const bevelled = rest.trim().startsWith("./");
    const rem = rest.trim().slice(bevelled ? 2 : 1);
    let next;
    let ascii;
 
    if (rem.startsWith(" ")) {
      const split = rem.trim().split(" ");
      next = parsegroup(split[0]);
      ascii = rem.trimLeft().slice(split[0].length + 1);
    } else {
      [next, ascii] = parseone(rem);
    }
    next = next || mrow("");
 
    const ml = mfrac(
      removeSurroundingBrackets(el) + removeSurroundingBrackets(next),
      bevelled && { bevelled: true }
    );
 
    if (
      (ascii && ascii.trim().startsWith("/")) ||
      ascii.trim().startsWith("./")
    ) {
      return splitNextFraction(ml, ascii);
    }
    return [ml, ascii];
  }
 
  function splitNextWhitespace(str) {
    const re = new RegExp(`(\\s|${options.colSep}|${options.rowSep}|$)`);
    const match = str.match(re);
    const head = str.slice(0, match.index);
    const sep = match[0];
    const tail = str.slice(match.index + 1);
 
    let next = head;
    let rest = sep + tail;
 
    if (!syntax.isgroupStart(tail.trim()) && syntax.endsInFunc(head)) {
      const newsplit = splitNextWhitespace(tail);
      next += sep + newsplit[0];
      [, rest] = newsplit;
    } else Iif (head.match(/root$/)) {
      const split1 = splitNextWhitespace(tail);
      const split2 = splitNextWhitespace(split1[1].trimLeft());
      next += `${sep + split1[0]} ${split2[0]}`;
      rest = sep + split2[1];
    }
    return [next, rest];
  }
 
  function parsetable(matrix, attrs) {
    const rows = (() => {
      const lines = colsplit(matrix);
      return lines.length > 1 ? lines : newlinesplit(matrix);
    })().map(el => el.trim().slice(1, -1));
 
    return mtable(rows.map(row => parserow(row)).join(""), attrs);
  }
 
  function parserow(row, acc = "") {
    if (!row || row.length === 0) {
      return mtr(acc);
    }
 
    const [mathml, rest] = parsecell(row.trim(), "");
    return parserow(rest.trim(), acc + mathml);
  }
 
  function parsecell(cell, acc) {
    if (!cell || cell.length === 0) {
      return [mtd(acc), ""];
    }
    if (cell[0] === options.colSep) {
      return [mtd(acc), cell.slice(1).trim()];
    }
 
    const [mathml, rest] = parseone(cell);
    return parsecell(rest.trim(), acc + mathml);
  }
 
  return parse;
}
 
function splitlast(mathml) {
  /**
   Return a pair of all but last eliment and the last eliment
   */
  const lastel = getlastel(mathml);
  const prewels = mathml.slice(0, mathml.lastIndexOf(lastel));
 
  return [prewels, lastel];
}
 
function removeSurroundingBrackets(mathml) {
  const inside = mathml
    .replace(/^<mfenced[^>]*>/, "")
    .replace(/<\/mfenced>$/, "");
  Eif (splitlast(inside)[1] === inside) {
    return inside;
  }
  return mrow(inside);
}
 
function getlastel(xmlstr) {
  // This breaks the linearity of the implimentation
  // optimation possible, perhaps an XML parser
  const tagmatch = xmlstr.match(/<\/(m[a-z]+)>$/);
  if (!tagmatch) {
    const spacematch = xmlstr.match(/<mspace\s*([a-z]+="[a-z]")*\s*\?>/);
    Iif (spacematch) {
      const i = spacematch.match[0].length;
      return xmlstr.slice(i);
    }
    return "";
  }
 
  const tagname = tagmatch[1];
 
  let i = xmlstr.length - (tagname.length + 3);
  let inners = 0;
  for (i; i >= 0; i -= 1) {
    if (xmlstr.slice(i).startsWith(`<${tagname}`)) {
      if (inners === 0) {
        break;
      }
      inners -= 1;
    }
    if (xmlstr.slice(i - 2).startsWith(`</${tagname}`)) {
      inners += 1;
    }
  }
 
  return xmlstr.slice(i);
}
 
function findmatching(str) {
  const open = str[0];
  let close = open;
 
  if (open === "(") {
    close = ")";
  } else Eif (open === "[") {
    close = "]";
  }
 
  let inners = 0;
  let index = 0;
  for (let i = 0; i < str.length; i += 1) {
    const char = str[i];
    index += 1;
    if (char === close) {
      inners -= 1;
      if (inners === 0) {
        break;
      }
    } else if (char === open) {
      inners += 1;
    }
  }
  return index;
}
 
function isempty(obj) {
  return Object.keys(obj).length === 0;
}
 
function contains(arr, el) {
  return arr.indexOf(el) >= 0;
}
 
function last(arr) {
  return arr.slice(-1)[0];
}
 
parser.getlastel = getlastel;
 
export default parser;