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];
75 char const * latex_special_chars = "#$%&_{}";
78 /// Read TeX into data, flags give stop conditions
79 void mathed_parse(MathArray & data, unsigned flags);
84 const unsigned char LM_TK_OPEN = '{';
85 const unsigned char LM_TK_CLOSE = '}';
88 FLAG_BRACE = 1 << 0, // A { needed //}
89 FLAG_BRACE_OPT = 1 << 2, // Optional {
90 FLAG_BRACE_LAST = 1 << 3, // Last } ends the parsing process
91 FLAG_BRACK_ARG = 1 << 4, // Optional [
92 FLAG_RIGHT = 1 << 5, // Next right ends the parsing process
93 FLAG_END = 1 << 6, // Next end ends the parsing process
94 FLAG_BRACE_FONT = 1 << 7, // Next } closes a font
95 FLAG_BRACK_END = 1 << 9, // Next ] ends the parsing process
96 FLAG_AMPERSAND = 1 << 10, // Next & ends the parsing process
97 FLAG_NEWLINE = 1 << 11 // Next \\ ends the parsing process
113 MathTextCodes yyvarcode;
117 struct latex_mathenv_type {
119 char const * basename;
125 latex_mathenv_type latex_mathenv[] = {
126 {"math", "math", LM_OT_SIMPLE, 0, 0},
127 {"equation*", "equation", LM_OT_EQUATION, 0, 0},
128 {"equation", "equation", LM_OT_EQUATION, 1, 0},
129 {"eqnarray*", "eqnarray", LM_OT_EQNARRAY, 0, 0},
130 {"eqnarray", "eqnarray", LM_OT_EQNARRAY, 1, 0},
131 {"align*", "align", LM_OT_ALIGN, 0, 1},
132 {"align", "align", LM_OT_ALIGN, 1, 1},
133 {"alignat*", "alignat", LM_OT_ALIGNAT, 0, 1},
134 {"alignat", "alignat", LM_OT_ALIGNAT, 1, 1},
135 {"multline*", "multline", LM_OT_MULTLINE, 0, 1},
136 {"multline", "multline", LM_OT_MULTLINE, 1, 1},
137 {"array", "array", LM_OT_MATRIX, 0, 1}
140 int const latex_mathenv_num = sizeof(latex_mathenv)/sizeof(latex_mathenv[0]);
144 void mathPrintError(string const & msg)
146 lyxerr << "Line ~" << yylineno << ": Math parse error: " << msg << endl;
152 for (int i = 0; i <= 255; ++i) {
154 lexcode[i] = LexDigit;
156 lexcode[i] = LexSpace;
158 lexcode[i] = LexAlpha;
161 lexcode['\t'] = lexcode['\f'] = lexcode[' '] = LexSpace;
162 lexcode['\n'] = LexNewLine;
163 lexcode['%'] = LexComment;
164 lexcode['#'] = LexArgument;
165 lexcode['+'] = lexcode['-'] = lexcode['*'] = lexcode['/']
166 = lexcode['<'] = lexcode['>'] = lexcode['='] = LexBOP;
168 lexcode['!'] = lexcode[','] = lexcode[':']
169 = lexcode[';'] = LexMathSpace;
171 lexcode['('] = lexcode[')'] = lexcode['|'] = lexcode['.'] =
172 lexcode['?'] = LexOther;
174 lexcode['\''] = lexcode['@'] = LexAlpha;
176 lexcode['['] = lexcode[']'] = lexcode['^'] = lexcode['_'] =
177 lexcode['&'] = LexSelf;
179 lexcode['\\'] = LexESC;
180 lexcode['{'] = LexOpen;
181 lexcode['}'] = LexClose;
185 unsigned char LexGetArg(unsigned char lf, bool accept_spaces = false)
187 while (yyis->good()) {
194 lyxerr << "Math parse error: unexpected '" << c << "'" << endl;
200 unsigned char rg = 0;
201 if (lf == '{') rg = '}';
202 if (lf == '[') rg = ']';
203 if (lf == '(') rg = ')';
205 lyxerr << "Math parse error: unknown bracket '" << lf << "'" << endl;
215 if ((c > ' ' || (c == ' ' && accept_spaces)) && bcnt > 0)
217 } while (bcnt > 0 && yyis->good());
225 static int init_done;
227 if (!init_done) LexInitCodes();
229 while (yyis->good()) {
232 lyxerr << "reading byte: '" << c << "' code: " << lexcode[c] << endl;
233 lyxerr << " code: " << lexcode['ΓΌ'] << endl;
235 if (yyvarcode == LM_TC_TEXTRM && c == ' ') {
238 } else if (lexcode[c] == LexNewLine) {
241 } else if (lexcode[c] == LexComment) {
244 } while (c != '\n' && yyis->good()); // eat comments
245 } else if (lexcode[c] == LexDigit
246 || lexcode[c] == LexOther
247 || lexcode[c] == LexMathSpace) {
250 } else if (lexcode[c] == LexAlpha) {
253 } else if (lexcode[c] == LexBOP) {
256 } else if (lexcode[c] == LexSelf) {
258 } else if (lexcode[c] == LexArgument) {
261 return LM_TK_ARGUMENT;
262 } else if (lexcode[c] == LexOpen) {
264 } else if (lexcode[c] == LexClose) {
266 } else if (lexcode[c] == LexESC) {
270 return LM_TK_NEWLINE;
273 yylval.i = LM_OT_SIMPLE;
277 yylval.i = LM_OT_SIMPLE;
281 yylval.i = LM_OT_EQUATION;
285 yylval.i = LM_OT_EQUATION;
288 if (contains(latex_special_chars, c)) {
290 return LM_TK_SPECIAL;
292 if (lexcode[c] == LexMathSpace) {
294 for (i = 0; i < 4 && static_cast<int>(c) != latex_mathspace[i][0]; ++i)
296 yylval.i = (i < 4) ? i : 0;
299 if (lexcode[c] == LexAlpha || lexcode[c] == LexDigit) {
301 while (lexcode[c] == LexAlpha || lexcode[c] == LexDigit) {
307 lyxerr << "reading: text '" << yytext << "'\n";
308 latexkeys const * l = in_word_set(yytext);
312 if (l->token == LM_TK_BEGIN || l->token == LM_TK_END) {
315 while (i < latex_mathenv_num && yytext != latex_mathenv[i].name)
318 } else if (l->token == LM_TK_SPACE)
330 // Accent hacks only for 0.12. Stolen from Cursor.
334 void setAccent(int ac)
336 if (ac > 0 && accent < 8)
337 nestaccent[accent++] = ac;
339 accent = 0; // consumed!
343 MathInset * doAccent(unsigned char c, MathTextCodes t)
347 for (int i = accent - 1; i >= 0; --i) {
349 ac = new MathAccentInset(c, t, nestaccent[i]);
351 ac = new MathAccentInset(ac, nestaccent[i]);
353 accent = 0; // consumed!
359 MathInset * doAccent(MathInset * p)
363 for (int i = accent - 1; i >= 0; --i) {
365 ac = new MathAccentInset(p, nestaccent[i]);
367 ac = new MathAccentInset(ac, nestaccent[i]);
369 accent = 0; // consumed!
375 void do_insert(MathArray & dat, MathInset * m)
378 dat.push_back(doAccent(m));
383 void do_insert(MathArray & dat, unsigned char ch, MathTextCodes fcode)
386 dat.push_back(doAccent(ch, fcode));
388 dat.push_back(ch, fcode);
392 void handle_frac(MathArray & dat, MathInsetTypes t)
394 MathFracInset * p = new MathFracInset(t);
395 mathed_parse(p->cell(0), FLAG_BRACE | FLAG_BRACE_LAST);
396 mathed_parse(p->cell(1), FLAG_BRACE | FLAG_BRACE_LAST);
401 MathScriptInset * lastScriptInset(MathArray & array)
403 MathInset * p = array.back_inset();
404 if (!p || !p->isScriptInset()) {
405 p = new MathScriptInset;
408 return static_cast<MathScriptInset *>(p);
415 static bool curr_num;
416 static string curr_label;
418 void mathed_parse_lines(MathInset * inset, int col, bool numbered, bool outmost)
420 // save global variables
421 bool saved_num = curr_num;
422 string saved_label = curr_label;
424 MathGridInset * p = static_cast<MathGridInset *>(inset);
425 for (int row = 0; true; ++row) {
426 // reset global variables
428 curr_label = string();
431 int idx = p->nargs() - p->ncols();
432 for (int i = 0; i < col - 1; ++i, ++idx)
433 mathed_parse(p->cell(idx), FLAG_AMPERSAND);
434 mathed_parse(p->cell(idx), FLAG_NEWLINE | FLAG_END);
437 MathMatrixInset * m = static_cast<MathMatrixInset *>(p);
438 m->numbered(row, curr_num);
439 m->label(row, curr_label);
450 // restore global variables
451 curr_num = saved_num;
452 curr_label = saved_label;
456 MathInset * mathed_parse()
462 case LM_TK_NEWCOMMAND: {
464 string name = yytext.substr(1);
467 unsigned char const c = yyis->peek();
470 na = atoi(yytext.c_str());
473 p = new MathMacroTemplate(name, na);
474 mathed_parse(p->cell(0), FLAG_BRACE | FLAG_BRACE_LAST);
475 lyxerr << "LM_TK_NEWCOMMAND: name: " << name << " na: " << na << "\n";
481 lyxerr << "reading math environment " << i << " "
482 << latex_mathenv[i].name << "\n";
484 MathInsetTypes typ = latex_mathenv[i].typ;
485 p = new MathMatrixInset(typ);
489 curr_num = latex_mathenv[i].numbered;
490 curr_label = string();
491 mathed_parse(p->cell(0), 0);
492 MathMatrixInset * m = static_cast<MathMatrixInset *>(p);
493 m->numbered(0, curr_num);
494 m->label(0, curr_label);
498 case LM_OT_EQUATION: {
499 curr_num = latex_mathenv[i].numbered;
500 curr_label = string();
501 mathed_parse(p->cell(0), FLAG_END);
502 MathMatrixInset * m = static_cast<MathMatrixInset *>(p);
503 m->numbered(0, curr_num);
504 m->label(0, curr_label);
508 case LM_OT_EQNARRAY: {
509 mathed_parse_lines(p, 3, latex_mathenv[i].numbered, true);
513 case LM_OT_ALIGNAT: {
515 //int c = atoi(yytext.c_str());
516 lyxerr << "LM_OT_ALIGNAT: not implemented\n";
517 mathed_parse_lines(p, 2, latex_mathenv[i].numbered, true);
518 lyxerr << "LM_OT_ALIGNAT: par: " << *p << "\n";
523 lyxerr << "1: unknown math environment: " << typ << "\n";
526 p->SetName(latex_mathenv[i].basename);
532 lyxerr << "2 unknown math environment: " << t << "\n";
539 void mathed_parse(MathArray & array, unsigned flags)
544 static int plevel = -1;
545 yyvarcode = LM_TC_VAR;
553 //lyxerr << "t: " << t << " flags: " << flags;
554 //array.dump(lyxerr);
557 if ((flags & FLAG_BRACE) && t != LM_TK_OPEN) {
558 if (!(flags & FLAG_BRACK_ARG) || t != '[') {
560 "Expected {. Maybe you forgot to enclose an argument in {}");
569 do_insert(array, yylval.i, yyvarcode);
573 array.push_back(new MathMacroArgument(yylval.i));
577 array.push_back(yylval.i, LM_TC_SPECIAL);
581 do_insert(array, yylval.i, LM_TC_CONST);
586 if (accent && tprev == LM_TK_ACCENT) {
587 acc_braces[acc_brace++] = brace;
590 if (flags & FLAG_BRACE_OPT) {
591 flags &= ~FLAG_BRACE_OPT;
595 if (flags & FLAG_BRACE)
596 flags &= ~FLAG_BRACE;
598 array.push_back('{', LM_TC_TEX);
604 mathPrintError("Unmatching braces");
608 if (acc_brace && brace == acc_braces[acc_brace - 1] - 1) {
612 if (flags & FLAG_BRACE_FONT) {
613 yyvarcode = LM_TC_VAR;
614 flags &= ~FLAG_BRACE_FONT;
617 if (brace == 0 && (flags & FLAG_BRACE_LAST)) {
621 array.push_back('}', LM_TC_TEX);
625 if (flags & FLAG_BRACK_ARG) {
626 flags &= ~FLAG_BRACK_ARG;
627 unsigned char const rg = LexGetArg('[');
629 mathPrintError("Expected ']'");
634 array.push_back('[', LM_TC_CONST);
638 if (flags & FLAG_BRACK_END) {
642 array.push_back(']', LM_TC_CONST);
648 mathed_parse(ar, FLAG_BRACE_OPT | FLAG_BRACE_LAST);
649 MathScriptInset * p = lastScriptInset(array);
658 mathed_parse(ar, FLAG_BRACE_OPT | FLAG_BRACE_LAST);
659 MathScriptInset * p = lastScriptInset(array);
667 MathScriptInset * p = lastScriptInset(array);
669 p->limits(yylval.l->id ? 1 : -1);
675 if (flags & FLAG_AMPERSAND) {
676 flags &= ~FLAG_AMPERSAND;
680 lyxerr << "found tab unexpectedly, array: '" << array << "'\n";
686 if (flags & FLAG_NEWLINE) {
687 flags &= ~FLAG_NEWLINE;
691 lyxerr << "found newline unexpectedly, array: '" << array << "'\n";
697 array.push_back(new MathBigopInset(yylval.l->name, yylval.l->id));
702 if (yylval.l->id < 256) {
703 MathTextCodes tc = MathIsBOPS(yylval.l->id) ? LM_TC_BOPS: LM_TC_SYMB;
704 do_insert(array, yylval.l->id, tc);
706 do_insert(array, new MathFuncInset(yylval.l->name));
710 do_insert(array, yylval.i, LM_TC_BOP);
715 array.push_back(new MathSpaceInset(yylval.i));
719 array.push_back(new MathDotsInset(yylval.l->name, yylval.l->id));
723 handle_frac(array, LM_OT_ATOP);
727 handle_frac(array, LM_OT_STACKREL);
731 handle_frac(array, LM_OT_FRAC);
739 MathRootInset * rt = new MathRootInset;
740 mathed_parse(rt->cell(0), FLAG_BRACK_END);
741 mathed_parse(rt->cell(1), FLAG_BRACE | FLAG_BRACE_LAST);
745 MathSqrtInset * sq = new MathSqrtInset;
746 mathed_parse(sq->cell(0), FLAG_BRACE | FLAG_BRACE_LAST);
757 else if (ld == LM_TK_STR || ld == LM_TK_BOP || ld == LM_TK_SPECIAL)
761 mathed_parse(ar, FLAG_RIGHT);
766 else if (rd == LM_TK_STR || rd == LM_TK_BOP || rd == LM_TK_SPECIAL)
769 MathDelimInset * dl = new MathDelimInset(ld, rd);
776 if (flags & FLAG_RIGHT) {
780 mathPrintError("Unmatched right delimiter");
785 yyvarcode = static_cast<MathTextCodes>(yylval.l->id);
786 flags |= (FLAG_BRACE | FLAG_BRACE_FONT);
791 lyxerr << "LM_TK_STY not implemented\n";
792 //MathArray tmp = array;
793 //MathSizeInset * p = new MathSizeInset(MathStyles(yylval.l->id));
794 //array.push_back(p);
795 //mathed_parse(p->cell(0), FLAG_BRACE_FONT);
802 MathDecorationInset * sq = new MathDecorationInset(yylval.l->id);
803 mathed_parse(sq->cell(0), FLAG_BRACE | FLAG_BRACE_LAST);
809 setAccent(yylval.l->id);
819 array.push_back(t, LM_TC_CONST);
821 array.push_back(new MathFuncInset(yylval.l->name));
825 array.push_back(new MathFuncInset(yylval.l->name, LM_OT_FUNCLIM));
829 if (MathMacroTable::hasTemplate(yytext)) {
830 MathMacro * m = MathMacroTable::cloneTemplate(yytext);
831 for (int i = 0; i < m->nargs(); ++i) {
832 mathed_parse(m->cell(i), FLAG_BRACE_OPT | FLAG_BRACE_LAST);
833 lyxerr << "reading cell " << i << " '" << m->cell(i) << "'\n";
836 lyxerr << "macro: " << *m << "\n";
837 m->Metrics(LM_ST_TEXT);
839 do_insert(array, new MathFuncInset(yytext, LM_OT_UNDEF));
849 MathInsetTypes typ = latex_mathenv[i].typ;
851 if (typ == LM_OT_MATRIX) {
852 string valign = "\0";
853 unsigned char rg = LexGetArg(0);
859 string halign = yytext;
860 MathArrayInset * mm = new MathArrayInset(halign.size(), 1);
862 mm->valign(valign[0]);
865 mathed_parse_lines(mm, halign.size(), latex_mathenv[i].numbered, false);
866 do_insert(array, mm);
867 //lyxerr << "read matrix " << *mm << "\n";
870 lyxerr << "unknow math inset " << typ << "\n";
875 do_insert(array, MathMacroTable::cloneTemplate(yylval.l->name));
880 unsigned char const rg = LexGetArg('\0', true);
882 mathPrintError("Expected '{'");
884 lyxerr << "[" << yytext << "]" << endl;
888 //lyxerr << " setting label to " << yytext << "\n";
894 mathPrintError("Unrecognized token");
895 lyxerr << "[" << t << " " << yytext << "]" << endl;
898 } // end of big switch
902 lyxerr << " Math Panic, expect problems!" << endl;
903 // Search for the end command.
906 } while (t != LM_TK_END && t);
910 if (flags & FLAG_BRACE_OPT) {
911 flags &= ~FLAG_BRACE_OPT;
919 MathInset * mathed_parse(istream & is)
923 return mathed_parse();
927 MathInset * mathed_parse(LyXLex & lex)
929 yyis = &lex.getStream();
930 yylineno = lex.GetLineNo();
932 MathInset * p = mathed_parse();
934 // Update line number
935 lex.setLineNo(yylineno);
937 // reading of end_inset
940 if (lex.GetString() == "\\end_inset")
942 lyxerr << "InsetFormula::Read: Garbage before \\end_inset,"
943 " or missing \\end_inset!" << endl;