3 * Purpose: Parser for mathed
4 * Author: Alejandro Aguilar Sierra <asierra@servidor.unam.mx>
5 * Created: January 1996
6 * Description: Parse LaTeX2e math mode code.
8 * Dependencies: Xlib, XForms
10 * Copyright: 1996, Alejandro Aguilar Sierra
14 * You are free to use and modify this code under the terms of
15 * the GNU General Public Licence version 2 or later.
23 #pragma implementation
26 #include "math_parser.h"
28 #include "math_inset.h"
29 #include "math_macro.h"
30 #include "math_macrotable.h"
31 #include "math_macrotemplate.h"
32 #include "math_root.h"
33 #include "math_arrayinset.h"
34 #include "math_sqrtinset.h"
35 #include "math_matrixinset.h"
36 #include "math_accentinset.h"
37 #include "math_bigopinset.h"
38 #include "math_funcinset.h"
39 #include "math_spaceinset.h"
40 #include "math_sizeinset.h"
41 #include "math_dotsinset.h"
42 #include "math_fracinset.h"
43 #include "math_deliminset.h"
44 #include "math_decorationinset.h"
46 #include "mathed/support.h"
54 // These are lexical codes, not semantic
60 LexBOP, // Binary operators or relations
72 lexcode_enum lexcode[256];
76 char const * latex_special_chars = "#$%&_{}";
79 /// Read TeX into data, flags give stop conditions
80 void mathed_parse(MathArray & data, unsigned flags);
85 const char LM_TK_OPEN = '{';
86 const char LM_TK_CLOSE = '}';
89 FLAG_BRACE = 1 << 0, // A { needed //}
90 FLAG_BRACE_OPT = 1 << 2, // Optional {
91 FLAG_BRACE_LAST = 1 << 3, // Last } ends the parsing process
92 FLAG_BRACK_ARG = 1 << 4, // Optional [
93 FLAG_RIGHT = 1 << 5, // Next right ends the parsing process
94 FLAG_END = 1 << 6, // Next end ends the parsing process
95 FLAG_BRACE_FONT = 1 << 7, // Next } closes a font
96 FLAG_BRACK_END = 1 << 9, // Next ] ends the parsing process
97 FLAG_AMPERSAND = 1 << 10, // Next & ends the parsing process
98 FLAG_NEWLINE = 1 << 11 // Next \\ ends the parsing process
115 bool yy_mtextmode = false;
119 struct latex_mathenv_type {
121 char const * basename;
127 latex_mathenv_type latex_mathenv[] = {
128 {"math", "math", LM_OT_SIMPLE, 0, 0},
129 {"equation*", "equation", LM_OT_EQUATION, 0, 0},
130 {"equation", "equation", LM_OT_EQUATION, 1, 0},
131 {"eqnarray*", "eqnarray", LM_OT_EQNARRAY, 0, 0},
132 {"eqnarray", "eqnarray", LM_OT_EQNARRAY, 1, 0},
133 {"align*", "align", LM_OT_ALIGN, 0, 1},
134 {"align", "align", LM_OT_ALIGN, 1, 1},
135 {"alignat*", "alignat", LM_OT_ALIGNAT, 0, 1},
136 {"alignat", "alignat", LM_OT_ALIGNAT, 1, 1},
137 {"multline*", "multline", LM_OT_MULTLINE, 0, 1},
138 {"multline", "multline", LM_OT_MULTLINE, 1, 1},
139 {"array", "array", LM_OT_MATRIX, 0, 1}
142 int const latex_mathenv_num = sizeof(latex_mathenv)/sizeof(latex_mathenv[0]);
146 void mathPrintError(string const & msg)
148 lyxerr << "Line ~" << yylineno << ": Math parse error: " << msg << endl;
154 for (int i = 0; i <= 255; ++i) {
156 lexcode[i] = LexAlpha;
158 lexcode[i] = LexDigit;
160 lexcode[i] = LexSpace;
162 lexcode[i] = LexNone;
165 lexcode['\t'] = lexcode['\f'] = lexcode[' '] = LexSpace;
166 lexcode['\n'] = LexNewLine;
167 lexcode['%'] = LexComment;
168 lexcode['#'] = LexArgument;
169 lexcode['+'] = lexcode['-'] = lexcode['*'] = lexcode['/']
170 = lexcode['<'] = lexcode['>'] = lexcode['='] = LexBOP;
172 lexcode['!'] = lexcode[','] = lexcode[':']
173 = lexcode[';'] = LexMathSpace;
175 lexcode['('] = lexcode[')'] = lexcode['|'] = lexcode['.'] =
176 lexcode['?'] = LexOther;
178 lexcode['\''] = lexcode['@'] = LexAlpha;
180 lexcode['['] = lexcode[']'] = lexcode['^'] = lexcode['_'] =
181 lexcode['&'] = LexSelf;
183 lexcode['\\'] = LexESC;
184 lexcode['{'] = LexOpen;
185 lexcode['}'] = LexClose;
189 char LexGetArg(char lf, bool accept_spaces = false)
191 while (yyis->good()) {
198 lyxerr << "Math parse error: unexpected '" << c << "'" << endl;
205 if (lf == '{') rg = '}';
206 if (lf == '[') rg = ']';
207 if (lf == '(') rg = ')';
209 lyxerr << "Math parse error: unknown bracket '" << lf << "'" << endl;
219 if ((c > ' ' || (c == ' ' && accept_spaces)) && bcnt > 0)
221 } while (bcnt > 0 && yyis->good());
229 static int init_done;
231 if (!init_done) LexInitCodes();
233 while (yyis->good()) {
237 if (yy_mtextmode && c == ' ') {
240 } else if (lexcode[c] == LexNewLine) {
243 } else if (lexcode[c] == LexComment) {
246 } while (c != '\n' && yyis->good()); // eat comments
247 } else if (lexcode[c] == LexDigit
248 || lexcode[c] == LexOther
249 || lexcode[c] == LexMathSpace) {
252 } else if (lexcode[c] == LexAlpha) {
255 } else if (lexcode[c] == LexBOP) {
258 } else if (lexcode[c] == LexSelf) {
260 } else if (lexcode[c] == LexArgument) {
263 return LM_TK_ARGUMENT;
264 } else if (lexcode[c] == LexOpen) {
266 } else if (lexcode[c] == LexClose) {
268 } else if (lexcode[c] == LexESC) {
272 return LM_TK_NEWLINE;
275 yylval.i = LM_OT_SIMPLE;
279 yylval.i = LM_OT_SIMPLE;
283 yylval.i = LM_OT_EQUATION;
287 yylval.i = LM_OT_EQUATION;
290 if (contains(latex_special_chars, c)) {
292 return LM_TK_SPECIAL;
294 if (lexcode[c] == LexMathSpace) {
296 for (i = 0; i < 4 && static_cast<int>(c) != latex_mathspace[i][0]; ++i)
298 yylval.i = (i < 4) ? i : 0;
301 if (lexcode[c] == LexAlpha || lexcode[c] == LexDigit) {
303 while (lexcode[c] == LexAlpha || lexcode[c] == LexDigit) {
309 lyxerr << "reading: text '" << yytext << "'\n";
310 latexkeys const * l = in_word_set(yytext);
314 if (l->token == LM_TK_BEGIN || l->token == LM_TK_END) {
317 while (i < latex_mathenv_num && yytext != latex_mathenv[i].name)
320 } else if (l->token == LM_TK_SPACE)
332 // Accent hacks only for 0.12. Stolen from Cursor.
336 void setAccent(int ac)
338 if (ac > 0 && accent < 8)
339 nestaccent[accent++] = ac;
341 accent = 0; // consumed!
345 MathInset * doAccent(byte c, MathTextCodes t)
349 for (int i = accent - 1; i >= 0; --i) {
351 ac = new MathAccentInset(c, t, nestaccent[i]);
353 ac = new MathAccentInset(ac, nestaccent[i]);
355 accent = 0; // consumed!
361 MathInset * doAccent(MathInset * p)
365 for (int i = accent - 1; i >= 0; --i) {
367 ac = new MathAccentInset(p, nestaccent[i]);
369 ac = new MathAccentInset(ac, nestaccent[i]);
371 accent = 0; // consumed!
377 void do_insert(MathArray & dat, MathInset * m)
380 dat.push_back(doAccent(m));
385 void do_insert(MathArray & dat, byte ch, MathTextCodes fcode)
388 dat.push_back(doAccent(ch, fcode));
390 dat.push_back(ch, fcode);
394 void handle_frac(MathArray & dat, MathInsetTypes t)
396 MathFracInset * p = new MathFracInset(t);
397 mathed_parse(p->cell(0), FLAG_BRACE | FLAG_BRACE_LAST);
398 mathed_parse(p->cell(1), FLAG_BRACE | FLAG_BRACE_LAST);
403 MathScriptInset * lastScriptInset(MathArray & array)
405 MathInset * p = array.back_inset();
406 if (!p || !p->isScriptInset()) {
407 p = new MathScriptInset;
410 return static_cast<MathScriptInset *>(p);
417 static bool curr_num;
418 static string curr_label;
420 void mathed_parse_lines(MathInset * inset, int col, bool numbered, bool outmost)
422 MathGridInset * p = static_cast<MathGridInset *>(inset);
423 for (int row = 0; true; ++row) {
424 // reset global variables
426 curr_label = string();
429 int idx = p->nargs() - p->ncols();
430 for (int i = 0; i < col - 1; ++i, ++idx)
431 mathed_parse(p->cell(idx), FLAG_AMPERSAND);
432 mathed_parse(p->cell(idx), FLAG_NEWLINE | FLAG_END);
435 MathMatrixInset * m = static_cast<MathMatrixInset *>(p);
436 m->numbered(row, curr_num);
437 m->label(row, curr_label);
450 MathInset * mathed_parse()
456 case LM_TK_NEWCOMMAND: {
458 string name = yytext.substr(1);
461 char const c = yyis->peek();
464 na = atoi(yytext.c_str());
467 p = new MathMacroTemplate(name, na);
468 mathed_parse(p->cell(0), FLAG_BRACE | FLAG_BRACE_LAST);
469 lyxerr << "LM_TK_NEWCOMMAND: name: " << name << " na: " << na << "\n";
475 lyxerr << "reading math environment " << i << " "
476 << latex_mathenv[i].name << "\n";
478 MathInsetTypes typ = latex_mathenv[i].typ;
479 p = new MathMatrixInset(typ);
483 curr_num = latex_mathenv[i].numbered;
484 curr_label = string();
485 mathed_parse(p->cell(0), 0);
486 MathMatrixInset * m = static_cast<MathMatrixInset *>(p);
487 m->numbered(0, curr_num);
488 m->label(0, curr_label);
492 case LM_OT_EQUATION: {
493 curr_num = latex_mathenv[i].numbered;
494 curr_label = string();
495 mathed_parse(p->cell(0), FLAG_END);
496 MathMatrixInset * m = static_cast<MathMatrixInset *>(p);
497 m->numbered(0, curr_num);
498 m->label(0, curr_label);
502 case LM_OT_EQNARRAY: {
503 mathed_parse_lines(p, 3, latex_mathenv[i].numbered, true);
507 case LM_OT_ALIGNAT: {
509 //int c = atoi(yytext.c_str());
510 lyxerr << "LM_OT_ALIGNAT: not implemented\n";
511 mathed_parse_lines(p, 2, latex_mathenv[i].numbered, true);
512 lyxerr << "LM_OT_ALIGNAT: par: " << *p << "\n";
517 lyxerr << "1: unknown math environment: " << typ << "\n";
520 p->SetName(latex_mathenv[i].basename);
526 lyxerr << "2 unknown math environment: " << t << "\n";
533 void mathed_parse(MathArray & array, unsigned flags)
538 static int plevel = -1;
539 MathTextCodes varcode = LM_TC_VAR;
547 //lyxerr << "t: " << t << " flags: " << flags;
548 //array.dump(lyxerr);
551 if ((flags & FLAG_BRACE) && t != LM_TK_OPEN) {
552 if (!(flags & FLAG_BRACK_ARG) || t != '[') {
554 "Expected {. Maybe you forgot to enclose an argument in {}");
563 do_insert(array, yylval.i, varcode);
567 array.push_back(new MathMacroArgument(yylval.i));
571 array.push_back(yylval.i, LM_TC_SPECIAL);
575 do_insert(array, yylval.i, LM_TC_CONST);
580 if (accent && tprev == LM_TK_ACCENT) {
581 acc_braces[acc_brace++] = brace;
584 if (flags & FLAG_BRACE_OPT) {
585 flags &= ~FLAG_BRACE_OPT;
589 if (flags & FLAG_BRACE)
590 flags &= ~FLAG_BRACE;
592 array.push_back('{', LM_TC_TEX);
598 mathPrintError("Unmatching braces");
602 if (acc_brace && brace == acc_braces[acc_brace - 1] - 1) {
606 if (flags & FLAG_BRACE_FONT) {
608 yy_mtextmode = false;
609 flags &= ~FLAG_BRACE_FONT;
612 if (brace == 0 && (flags & FLAG_BRACE_LAST)) {
616 array.push_back('}', LM_TC_TEX);
620 if (flags & FLAG_BRACK_ARG) {
621 flags &= ~FLAG_BRACK_ARG;
622 char const rg = LexGetArg('[');
624 mathPrintError("Expected ']'");
629 array.push_back('[', LM_TC_CONST);
633 if (flags & FLAG_BRACK_END) {
637 array.push_back(']', LM_TC_CONST);
643 mathed_parse(ar, FLAG_BRACE_OPT | FLAG_BRACE_LAST);
644 MathScriptInset * p = lastScriptInset(array);
653 mathed_parse(ar, FLAG_BRACE_OPT | FLAG_BRACE_LAST);
654 MathScriptInset * p = lastScriptInset(array);
662 MathScriptInset * p = lastScriptInset(array);
664 p->limits(yylval.l->id ? 1 : -1);
670 if (flags & FLAG_AMPERSAND) {
671 flags &= ~FLAG_AMPERSAND;
675 lyxerr << "found tab unexpectedly, array: '" << array << "'\n";
681 if (flags & FLAG_NEWLINE) {
682 flags &= ~FLAG_NEWLINE;
686 lyxerr << "found newline unexpectedly, array: '" << array << "'\n";
692 array.push_back(new MathBigopInset(yylval.l->name, yylval.l->id));
697 if (yylval.l->id < 256) {
698 MathTextCodes tc = MathIsBOPS(yylval.l->id) ? LM_TC_BOPS: LM_TC_SYMB;
699 do_insert(array, yylval.l->id, tc);
701 do_insert(array, new MathFuncInset(yylval.l->name));
705 do_insert(array, yylval.i, LM_TC_BOP);
710 array.push_back(new MathSpaceInset(yylval.i));
714 array.push_back(new MathDotsInset(yylval.l->name, yylval.l->id));
718 handle_frac(array, LM_OT_ATOP);
722 handle_frac(array, LM_OT_STACKREL);
726 handle_frac(array, LM_OT_FRAC);
734 MathRootInset * rt = new MathRootInset;
735 mathed_parse(rt->cell(0), FLAG_BRACK_END);
736 mathed_parse(rt->cell(1), FLAG_BRACE | FLAG_BRACE_LAST);
740 MathSqrtInset * sq = new MathSqrtInset;
741 mathed_parse(sq->cell(0), FLAG_BRACE | FLAG_BRACE_LAST);
752 else if (ld == LM_TK_STR || ld == LM_TK_BOP || ld == LM_TK_SPECIAL)
756 mathed_parse(ar, FLAG_RIGHT);
761 else if (rd == LM_TK_STR || rd == LM_TK_BOP || rd == LM_TK_SPECIAL)
764 MathDelimInset * dl = new MathDelimInset(ld, rd);
771 if (flags & FLAG_RIGHT) {
775 mathPrintError("Unmatched right delimiter");
780 yy_mtextmode = (yylval.l->id == LM_TC_TEXTRM);
781 flags |= (FLAG_BRACE | FLAG_BRACE_FONT);
786 lyxerr << "LM_TK_STY not implemented\n";
787 //MathArray tmp = array;
788 //MathSizeInset * p = new MathSizeInset(MathStyles(yylval.l->id));
789 //array.push_back(p);
790 //mathed_parse(p->cell(0), FLAG_BRACE_FONT);
797 MathDecorationInset * sq = new MathDecorationInset(yylval.l->id);
798 mathed_parse(sq->cell(0), FLAG_BRACE | FLAG_BRACE_LAST);
804 setAccent(yylval.l->id);
814 array.push_back(t, LM_TC_CONST);
816 array.push_back(new MathFuncInset(yylval.l->name));
820 array.push_back(new MathFuncInset(yylval.l->name, LM_OT_FUNCLIM));
824 if (MathMacroTable::hasTemplate(yytext)) {
825 MathMacro * m = MathMacroTable::cloneTemplate(yytext);
826 for (int i = 0; i < m->nargs(); ++i) {
827 mathed_parse(m->cell(i), FLAG_BRACE_OPT | FLAG_BRACE_LAST);
828 lyxerr << "reading cell " << i << " '" << m->cell(i) << "'\n";
832 do_insert(array, new MathFuncInset(yytext, LM_OT_UNDEF));
842 MathInsetTypes typ = latex_mathenv[i].typ;
844 if (typ == LM_OT_MATRIX) {
845 string valign = "\0";
846 char rg = LexGetArg(0);
852 string halign = yytext;
853 MathArrayInset * mm = new MathArrayInset(halign.size(), 1);
855 mm->valign(valign[0]);
858 mathed_parse_lines(mm, halign.size(), latex_mathenv[i].numbered, false);
859 do_insert(array, mm);
860 //lyxerr << "read matrix " << *mm << "\n";
863 lyxerr << "unknow math inset " << typ << "\n";
868 do_insert(array, MathMacroTable::cloneTemplate(yylval.l->name));
873 char const rg = LexGetArg('\0', true);
875 mathPrintError("Expected '{'");
877 lyxerr << "[" << yytext << "]" << endl;
881 //lyxerr << " setting label to " << yytext << "\n";
887 mathPrintError("Unrecognized token");
888 lyxerr << "[" << t << " " << yytext << "]" << endl;
891 } // end of big switch
895 lyxerr << " Math Panic, expect problems!" << endl;
896 // Search for the end command.
899 } while (t != LM_TK_END && t);
903 if (flags & FLAG_BRACE_OPT) {
904 flags &= ~FLAG_BRACE_OPT;
912 MathInset * mathed_parse(istream & is)
916 return mathed_parse();
920 MathInset * mathed_parse(LyXLex & lex)
922 yyis = &lex.getStream();
923 yylineno = lex.GetLineNo();
925 MathInset * p = mathed_parse();
927 // Update line number
928 lex.setLineNo(yylineno);
930 // reading of end_inset
933 if (lex.GetString() == "\\end_inset")
935 lyxerr << "InsetFormula::Read: Garbage before \\end_inset,"
936 " or missing \\end_inset!" << endl;