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 unsigned char getuchar(std::istream * is)
88 return static_cast<unsigned char>(c);
91 const unsigned char LM_TK_OPEN = '{';
92 const unsigned char LM_TK_CLOSE = '}';
95 FLAG_BRACE = 1 << 0, // A { needed //}
96 FLAG_BRACE_OPT = 1 << 2, // Optional {
97 FLAG_BRACE_LAST = 1 << 3, // Last } ends the parsing process
98 FLAG_BRACK_ARG = 1 << 4, // Optional [
99 FLAG_RIGHT = 1 << 5, // Next right ends the parsing process
100 FLAG_END = 1 << 6, // Next end ends the parsing process
101 FLAG_BRACE_FONT = 1 << 7, // Next } closes a font
102 FLAG_BRACK_END = 1 << 9, // Next ] ends the parsing process
103 FLAG_AMPERSAND = 1 << 10, // Next & ends the parsing process
104 FLAG_NEWLINE = 1 << 11 // Next \\ ends the parsing process
120 MathTextCodes yyvarcode;
124 struct latex_mathenv_type {
126 char const * basename;
132 latex_mathenv_type latex_mathenv[] = {
133 {"math", "math", LM_OT_SIMPLE, 0, 0},
134 {"equation*", "equation", LM_OT_EQUATION, 0, 0},
135 {"equation", "equation", LM_OT_EQUATION, 1, 0},
136 {"eqnarray*", "eqnarray", LM_OT_EQNARRAY, 0, 0},
137 {"eqnarray", "eqnarray", LM_OT_EQNARRAY, 1, 0},
138 {"align*", "align", LM_OT_ALIGN, 0, 1},
139 {"align", "align", LM_OT_ALIGN, 1, 1},
140 {"alignat*", "alignat", LM_OT_ALIGNAT, 0, 1},
141 {"alignat", "alignat", LM_OT_ALIGNAT, 1, 1},
142 {"multline*", "multline", LM_OT_MULTLINE, 0, 1},
143 {"multline", "multline", LM_OT_MULTLINE, 1, 1},
144 {"array", "array", LM_OT_MATRIX, 0, 1}
147 int const latex_mathenv_num = sizeof(latex_mathenv)/sizeof(latex_mathenv[0]);
151 void mathPrintError(string const & msg)
153 lyxerr[Debug::MATHED] << "Line ~" << yylineno << ": Math parse error: " << msg << endl;
159 for (int i = 0; i <= 255; ++i) {
161 lexcode[i] = LexDigit;
163 lexcode[i] = LexSpace;
165 lexcode[i] = LexAlpha;
168 lexcode['\t'] = lexcode['\f'] = lexcode[' '] = LexSpace;
169 lexcode['\n'] = LexNewLine;
170 lexcode['%'] = LexComment;
171 lexcode['#'] = LexArgument;
172 lexcode['+'] = lexcode['-'] = lexcode['*'] = lexcode['/']
173 = lexcode['<'] = lexcode['>'] = lexcode['='] = LexBOP;
175 lexcode['!'] = lexcode[','] = lexcode[':']
176 = lexcode[';'] = LexMathSpace;
178 lexcode['('] = lexcode[')'] = lexcode['|'] = lexcode['.'] =
179 lexcode['?'] = LexOther;
181 lexcode['\''] = lexcode['@'] = LexAlpha;
183 lexcode['['] = lexcode[']'] = lexcode['^'] = lexcode['_'] =
184 lexcode['&'] = LexSelf;
186 lexcode['\\'] = LexESC;
187 lexcode['{'] = LexOpen;
188 lexcode['}'] = LexClose;
192 unsigned char LexGetArg(unsigned char lf, bool accept_spaces = false)
194 while (yyis->good()) {
195 unsigned char c = getuchar(yyis);
200 lyxerr[Debug::MATHED] << "Math parse error: unexpected '" << c << "'" << endl;
206 unsigned char rg = 0;
207 if (lf == '{') rg = '}';
208 if (lf == '[') rg = ']';
209 if (lf == '(') rg = ')';
211 lyxerr[Debug::MATHED] << "Math parse error: unknown bracket '" << lf << "'" << endl;
217 unsigned char c = getuchar(yyis);
220 if ((c > ' ' || (c == ' ' && accept_spaces)) && bcnt > 0)
222 } while (bcnt > 0 && yyis->good());
230 static int init_done;
232 if (!init_done) LexInitCodes();
234 while (yyis->good()) {
235 unsigned char c = getuchar(yyis);
236 //lyxerr << "reading byte: '" << c << "' code: " << lexcode[c] << endl;
238 if (yyvarcode == LM_TC_TEXTRM && c == ' ') {
241 } else if (lexcode[c] == LexNewLine) {
244 } else if (lexcode[c] == LexComment) {
247 } while (c != '\n' && yyis->good()); // eat comments
248 } else if (lexcode[c] == LexDigit
249 || lexcode[c] == LexOther
250 || lexcode[c] == LexMathSpace) {
253 } else if (lexcode[c] == LexAlpha) {
256 } else if (lexcode[c] == LexBOP) {
259 } else if (lexcode[c] == LexSelf) {
261 } else if (lexcode[c] == LexArgument) {
264 return LM_TK_ARGUMENT;
265 } else if (lexcode[c] == LexOpen) {
267 } else if (lexcode[c] == LexClose) {
269 } else if (lexcode[c] == LexESC) {
273 return LM_TK_NEWLINE;
276 yylval.i = LM_OT_SIMPLE;
280 yylval.i = LM_OT_SIMPLE;
284 yylval.i = LM_OT_EQUATION;
288 yylval.i = LM_OT_EQUATION;
291 if (contains(latex_special_chars, c)) {
293 return LM_TK_SPECIAL;
295 if (lexcode[c] == LexMathSpace) {
297 for (i = 0; i < 4 && static_cast<int>(c) != latex_mathspace[i][0]; ++i)
299 yylval.i = (i < 4) ? i : 0;
302 if (lexcode[c] == LexAlpha || lexcode[c] == LexDigit) {
304 while (lexcode[c] == LexAlpha || lexcode[c] == LexDigit) {
310 lyxerr[Debug::MATHED] << "reading: text '" << yytext << "'\n";
311 latexkeys const * l = in_word_set(yytext);
315 if (l->token == LM_TK_BEGIN || l->token == LM_TK_END) {
318 while (i < latex_mathenv_num && yytext != latex_mathenv[i].name)
321 } else if (l->token == LM_TK_SPACE)
333 // Accent hacks only for 0.12. Stolen from Cursor.
337 void setAccent(int ac)
339 if (ac > 0 && accent < 8)
340 nestaccent[accent++] = ac;
342 accent = 0; // consumed!
346 MathInset * doAccent(unsigned char c, MathTextCodes t)
350 for (int i = accent - 1; i >= 0; --i) {
352 ac = new MathAccentInset(c, t, nestaccent[i]);
354 ac = new MathAccentInset(ac, nestaccent[i]);
356 accent = 0; // consumed!
362 MathInset * doAccent(MathInset * p)
366 for (int i = accent - 1; i >= 0; --i) {
368 ac = new MathAccentInset(p, nestaccent[i]);
370 ac = new MathAccentInset(ac, nestaccent[i]);
372 accent = 0; // consumed!
378 void do_insert(MathArray & dat, MathInset * m)
381 dat.push_back(doAccent(m));
386 void do_insert(MathArray & dat, unsigned char ch, MathTextCodes fcode)
389 dat.push_back(doAccent(ch, fcode));
391 dat.push_back(ch, fcode);
395 void handle_frac(MathArray & dat, MathInsetTypes t)
397 MathFracInset * p = new MathFracInset(t);
398 mathed_parse(p->cell(0), FLAG_BRACE | FLAG_BRACE_LAST);
399 mathed_parse(p->cell(1), FLAG_BRACE | FLAG_BRACE_LAST);
404 MathScriptInset * lastScriptInset(MathArray & array)
406 MathInset * p = array.back_inset();
407 if (!p || !p->isScriptInset()) {
408 p = new MathScriptInset;
411 return static_cast<MathScriptInset *>(p);
418 static bool curr_num;
419 static string curr_label;
421 void mathed_parse_lines(MathInset * inset, int col, bool numbered, bool outmost)
423 // save global variables
424 bool saved_num = curr_num;
425 string saved_label = curr_label;
427 MathGridInset * p = static_cast<MathGridInset *>(inset);
428 for (int row = 0; true; ++row) {
429 // reset global variables
431 curr_label = string();
434 int idx = p->nargs() - p->ncols();
435 for (int i = 0; i < col - 1; ++i, ++idx)
436 mathed_parse(p->cell(idx), FLAG_AMPERSAND);
437 mathed_parse(p->cell(idx), FLAG_NEWLINE | FLAG_END);
440 MathMatrixInset * m = static_cast<MathMatrixInset *>(p);
441 m->numbered(row, curr_num);
442 m->label(row, curr_label);
453 // restore global variables
454 curr_num = saved_num;
455 curr_label = saved_label;
459 MathInset * mathed_parse()
465 case LM_TK_NEWCOMMAND: {
467 string name = yytext.substr(1);
470 unsigned char const c = yyis->peek();
473 na = atoi(yytext.c_str());
476 p = new MathMacroTemplate(name, na);
477 mathed_parse(p->cell(0), FLAG_BRACE | FLAG_BRACE_LAST);
478 lyxerr[Debug::MATHED] << "LM_TK_NEWCOMMAND: name: " << name << " na: " << na << "\n";
484 lyxerr[Debug::MATHED] << "reading math environment " << i << " "
485 << latex_mathenv[i].name << "\n";
487 MathInsetTypes typ = latex_mathenv[i].typ;
488 p = new MathMatrixInset(typ);
492 curr_num = latex_mathenv[i].numbered;
493 curr_label = string();
494 mathed_parse(p->cell(0), 0);
495 MathMatrixInset * m = static_cast<MathMatrixInset *>(p);
496 m->numbered(0, curr_num);
497 m->label(0, curr_label);
501 case LM_OT_EQUATION: {
502 curr_num = latex_mathenv[i].numbered;
503 curr_label = string();
504 mathed_parse(p->cell(0), FLAG_END);
505 MathMatrixInset * m = static_cast<MathMatrixInset *>(p);
506 m->numbered(0, curr_num);
507 m->label(0, curr_label);
511 case LM_OT_EQNARRAY: {
512 mathed_parse_lines(p, 3, latex_mathenv[i].numbered, true);
516 case LM_OT_ALIGNAT: {
518 //int c = atoi(yytext.c_str());
519 lyxerr[Debug::MATHED] << "LM_OT_ALIGNAT: not implemented\n";
520 mathed_parse_lines(p, 2, latex_mathenv[i].numbered, true);
521 lyxerr[Debug::MATHED] << "LM_OT_ALIGNAT: par: " << *p << "\n";
526 lyxerr[Debug::MATHED] << "1: unknown math environment: " << typ << "\n";
529 p->SetName(latex_mathenv[i].basename);
535 lyxerr[Debug::MATHED] << "2 unknown math environment: " << t << "\n";
542 void mathed_parse(MathArray & array, unsigned flags)
547 static int plevel = -1;
548 yyvarcode = LM_TC_VAR;
556 //lyxerr << "t: " << t << " flags: " << flags;
557 //array.dump(lyxerr);
560 if ((flags & FLAG_BRACE) && t != LM_TK_OPEN) {
561 if (!(flags & FLAG_BRACK_ARG) || t != '[') {
563 "Expected {. Maybe you forgot to enclose an argument in {}");
572 do_insert(array, yylval.i, yyvarcode);
576 array.push_back(new MathMacroArgument(yylval.i));
580 array.push_back(yylval.i, LM_TC_SPECIAL);
584 do_insert(array, yylval.i, LM_TC_CONST);
589 if (accent && tprev == LM_TK_ACCENT) {
590 acc_braces[acc_brace++] = brace;
593 if (flags & FLAG_BRACE_OPT) {
594 flags &= ~FLAG_BRACE_OPT;
598 if (flags & FLAG_BRACE)
599 flags &= ~FLAG_BRACE;
601 array.push_back('{', LM_TC_TEX);
607 mathPrintError("Unmatching braces");
611 if (acc_brace && brace == acc_braces[acc_brace - 1] - 1) {
615 if (flags & FLAG_BRACE_FONT) {
616 yyvarcode = LM_TC_VAR;
617 flags &= ~FLAG_BRACE_FONT;
620 if (brace == 0 && (flags & FLAG_BRACE_LAST)) {
624 array.push_back('}', LM_TC_TEX);
628 if (flags & FLAG_BRACK_ARG) {
629 flags &= ~FLAG_BRACK_ARG;
630 unsigned char const rg = LexGetArg('[');
632 mathPrintError("Expected ']'");
637 array.push_back('[', LM_TC_CONST);
641 if (flags & FLAG_BRACK_END) {
645 array.push_back(']', LM_TC_CONST);
651 mathed_parse(ar, FLAG_BRACE_OPT | FLAG_BRACE_LAST);
652 MathScriptInset * p = lastScriptInset(array);
661 mathed_parse(ar, FLAG_BRACE_OPT | FLAG_BRACE_LAST);
662 MathScriptInset * p = lastScriptInset(array);
670 MathScriptInset * p = lastScriptInset(array);
672 p->limits(yylval.l->id ? 1 : -1);
678 if (flags & FLAG_AMPERSAND) {
679 flags &= ~FLAG_AMPERSAND;
683 lyxerr[Debug::MATHED] << "found tab unexpectedly, array: '" << array << "'\n";
689 if (flags & FLAG_NEWLINE) {
690 flags &= ~FLAG_NEWLINE;
694 lyxerr[Debug::MATHED] << "found newline unexpectedly, array: '" << array << "'\n";
700 array.push_back(new MathBigopInset(yylval.l->name, yylval.l->id));
705 if (yylval.l->id < 256) {
706 MathTextCodes tc = MathIsBOPS(yylval.l->id) ? LM_TC_BOPS: LM_TC_SYMB;
707 do_insert(array, yylval.l->id, tc);
709 do_insert(array, new MathFuncInset(yylval.l->name));
713 do_insert(array, yylval.i, LM_TC_BOP);
718 array.push_back(new MathSpaceInset(yylval.i));
722 array.push_back(new MathDotsInset(yylval.l->name, yylval.l->id));
726 handle_frac(array, LM_OT_ATOP);
730 handle_frac(array, LM_OT_STACKREL);
734 handle_frac(array, LM_OT_FRAC);
739 unsigned char c = getuchar(yyis);
741 MathRootInset * rt = new MathRootInset;
742 mathed_parse(rt->cell(0), FLAG_BRACK_END);
743 mathed_parse(rt->cell(1), FLAG_BRACE | FLAG_BRACE_LAST);
747 MathSqrtInset * sq = new MathSqrtInset;
748 mathed_parse(sq->cell(0), FLAG_BRACE | FLAG_BRACE_LAST);
759 else if (ld == LM_TK_STR || ld == LM_TK_BOP || ld == LM_TK_SPECIAL)
763 mathed_parse(ar, FLAG_RIGHT);
768 else if (rd == LM_TK_STR || rd == LM_TK_BOP || rd == LM_TK_SPECIAL)
771 MathDelimInset * dl = new MathDelimInset(ld, rd);
778 if (flags & FLAG_RIGHT) {
782 mathPrintError("Unmatched right delimiter");
787 yyvarcode = static_cast<MathTextCodes>(yylval.l->id);
788 flags |= (FLAG_BRACE | FLAG_BRACE_FONT);
793 lyxerr[Debug::MATHED] << "LM_TK_STY not implemented\n";
794 //MathArray tmp = array;
795 //MathSizeInset * p = new MathSizeInset(MathStyles(yylval.l->id));
796 //array.push_back(p);
797 //mathed_parse(p->cell(0), FLAG_BRACE_FONT);
804 MathDecorationInset * sq = new MathDecorationInset(yylval.l->id);
805 mathed_parse(sq->cell(0), FLAG_BRACE | FLAG_BRACE_LAST);
811 setAccent(yylval.l->id);
821 array.push_back(t, LM_TC_CONST);
823 array.push_back(new MathFuncInset(yylval.l->name));
827 array.push_back(new MathFuncInset(yylval.l->name, LM_OT_FUNCLIM));
831 if (MathMacroTable::hasTemplate(yytext)) {
832 MathMacro * m = MathMacroTable::cloneTemplate(yytext);
833 for (int i = 0; i < m->nargs(); ++i)
834 mathed_parse(m->cell(i), FLAG_BRACE_OPT | FLAG_BRACE_LAST);
836 m->Metrics(LM_ST_TEXT);
838 do_insert(array, new MathFuncInset(yytext, LM_OT_UNDEF));
848 MathInsetTypes typ = latex_mathenv[i].typ;
850 if (typ == LM_OT_MATRIX) {
851 string valign = "\0";
852 unsigned char rg = LexGetArg(0);
858 string halign = yytext;
859 MathArrayInset * mm = new MathArrayInset(halign.size(), 1);
861 mm->valign(valign[0]);
864 mathed_parse_lines(mm, halign.size(), latex_mathenv[i].numbered, false);
865 do_insert(array, mm);
866 //lyxerr << "read matrix " << *mm << "\n";
869 lyxerr[Debug::MATHED] << "unknow math inset " << typ << "\n";
874 do_insert(array, MathMacroTable::cloneTemplate(yylval.l->name));
879 unsigned char const rg = LexGetArg('\0', true);
881 mathPrintError("Expected '{'");
883 lyxerr[Debug::MATHED] << "[" << yytext << "]" << endl;
887 //lyxerr << " setting label to " << yytext << "\n";
893 mathPrintError("Unrecognized token");
894 lyxerr[Debug::MATHED] << "[" << t << " " << yytext << "]" << endl;
897 } // end of big switch
901 lyxerr << " Math Panic, expect problems!" << endl;
902 // Search for the end command.
905 } while (t != LM_TK_END && t);
909 if (flags & FLAG_BRACE_OPT) {
910 flags &= ~FLAG_BRACE_OPT;
918 MathInset * mathed_parse(istream & is)
922 return mathed_parse();
926 MathInset * mathed_parse(LyXLex & lex)
928 yyis = &lex.getStream();
929 yylineno = lex.GetLineNo();
931 MathInset * p = mathed_parse();
933 // Update line number
934 lex.setLineNo(yylineno);
936 // reading of end_inset
939 if (lex.GetString() == "\\end_inset")
941 lyxerr[Debug::MATHED] << "InsetFormula::Read: Garbage before \\end_inset,"
942 " or missing \\end_inset!" << endl;