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 bool init_done = false;
237 while (yyis->good()) {
238 unsigned char c = getuchar(yyis);
239 //lyxerr << "reading byte: '" << c << "' code: " << lexcode[c] << endl;
241 if (yyvarcode == LM_TC_TEXTRM && c == ' ') {
244 } else if (lexcode[c] == LexNewLine) {
247 } else if (lexcode[c] == LexComment) {
250 } while (c != '\n' && yyis->good()); // eat comments
251 } else if (lexcode[c] == LexDigit
252 || lexcode[c] == LexOther
253 || lexcode[c] == LexMathSpace) {
256 } else if (lexcode[c] == LexAlpha) {
259 } else if (lexcode[c] == LexBOP) {
262 } else if (lexcode[c] == LexSelf) {
264 } else if (lexcode[c] == LexArgument) {
267 return LM_TK_ARGUMENT;
268 } else if (lexcode[c] == LexOpen) {
270 } else if (lexcode[c] == LexClose) {
272 } else if (lexcode[c] == LexESC) {
276 return LM_TK_NEWLINE;
279 yylval.i = LM_OT_SIMPLE;
283 yylval.i = LM_OT_SIMPLE;
287 yylval.i = LM_OT_EQUATION;
291 yylval.i = LM_OT_EQUATION;
294 if (contains(latex_special_chars, c)) {
296 return LM_TK_SPECIAL;
298 if (lexcode[c] == LexMathSpace) {
300 for (i = 0; i < 4 && static_cast<int>(c) != latex_mathspace[i][0]; ++i)
302 yylval.i = (i < 4) ? i : 0;
305 if (lexcode[c] == LexAlpha || lexcode[c] == LexDigit) {
307 while (lexcode[c] == LexAlpha || lexcode[c] == LexDigit) {
313 lyxerr[Debug::MATHED] << "reading: text '" << yytext << "'\n";
314 latexkeys const * l = in_word_set(yytext);
318 if (l->token == LM_TK_BEGIN || l->token == LM_TK_END) {
321 while (i < latex_mathenv_num && yytext != latex_mathenv[i].name)
324 } else if (l->token == LM_TK_SPACE)
336 void handle_frac(MathArray & dat, string const & name)
338 MathFracInset * p = new MathFracInset(name);
339 mathed_parse(p->cell(0), FLAG_BRACE | FLAG_BRACE_LAST);
340 mathed_parse(p->cell(1), FLAG_BRACE | FLAG_BRACE_LAST);
345 MathScriptInset * lastScriptInset(MathArray & array)
347 MathInset * p = array.back_inset();
348 if (!p || !p->isScriptInset()) {
349 p = new MathScriptInset;
352 return static_cast<MathScriptInset *>(p);
359 static bool curr_num;
360 static string curr_label;
362 void mathed_parse_lines(MathInset * inset, int col, bool numbered, bool outmost)
364 // save global variables
365 bool saved_num = curr_num;
366 string saved_label = curr_label;
368 MathGridInset * p = static_cast<MathGridInset *>(inset);
369 for (int row = 0; true; ++row) {
370 // reset global variables
372 curr_label = string();
375 int idx = p->nargs() - p->ncols();
376 for (int i = 0; i < col - 1; ++i, ++idx)
377 mathed_parse(p->cell(idx), FLAG_AMPERSAND);
378 mathed_parse(p->cell(idx), FLAG_NEWLINE | FLAG_END);
381 MathMatrixInset * m = static_cast<MathMatrixInset *>(p);
382 m->numbered(row, curr_num);
383 m->label(row, curr_label);
394 // restore global variables
395 curr_num = saved_num;
396 curr_label = saved_label;
400 MathInset * mathed_parse()
406 case LM_TK_NEWCOMMAND: {
408 string name = yytext.substr(1);
411 unsigned char const c = yyis->peek();
414 na = atoi(yytext.c_str());
417 p = new MathMacroTemplate(name, na);
418 mathed_parse(p->cell(0), FLAG_BRACE | FLAG_BRACE_LAST);
419 lyxerr[Debug::MATHED] << "LM_TK_NEWCOMMAND: name: " << name << " na: " << na << "\n";
425 lyxerr[Debug::MATHED] << "reading math environment " << i << " "
426 << latex_mathenv[i].name << "\n";
428 MathInsetTypes typ = latex_mathenv[i].typ;
429 p = new MathMatrixInset(typ);
433 curr_num = latex_mathenv[i].numbered;
434 curr_label = string();
435 mathed_parse(p->cell(0), 0);
436 MathMatrixInset * m = static_cast<MathMatrixInset *>(p);
437 m->numbered(0, curr_num);
438 m->label(0, curr_label);
442 case LM_OT_EQUATION: {
443 curr_num = latex_mathenv[i].numbered;
444 curr_label = string();
445 mathed_parse(p->cell(0), FLAG_END);
446 MathMatrixInset * m = static_cast<MathMatrixInset *>(p);
447 m->numbered(0, curr_num);
448 m->label(0, curr_label);
452 case LM_OT_EQNARRAY: {
453 mathed_parse_lines(p, 3, latex_mathenv[i].numbered, true);
457 case LM_OT_ALIGNAT: {
459 //int c = atoi(yytext.c_str());
460 lyxerr[Debug::MATHED] << "LM_OT_ALIGNAT: not implemented\n";
461 mathed_parse_lines(p, 2, latex_mathenv[i].numbered, true);
462 lyxerr[Debug::MATHED] << "LM_OT_ALIGNAT: par: " << *p << "\n";
467 lyxerr[Debug::MATHED] << "1: unknown math environment: " << typ << "\n";
470 p->SetName(latex_mathenv[i].basename);
476 lyxerr[Debug::MATHED] << "2 unknown math environment: " << t << "\n";
483 void mathed_parse(MathArray & array, unsigned flags)
488 static int plevel = -1;
489 yyvarcode = LM_TC_VAR;
495 //lyxerr << "t: " << t << " flags: " << flags;
496 //array.dump(lyxerr);
499 if ((flags & FLAG_BRACE) && t != LM_TK_OPEN) {
500 if (!(flags & FLAG_BRACK_ARG) || t != '[') {
502 "Expected {. Maybe you forgot to enclose an argument in {}");
511 array.push_back(yylval.i, yyvarcode);
515 array.push_back(new MathMacroArgument(yylval.i));
519 array.push_back(yylval.i, LM_TC_SPECIAL);
523 array.push_back(yylval.i, LM_TC_CONST);
528 if (flags & FLAG_BRACE_OPT) {
529 flags &= ~FLAG_BRACE_OPT;
533 if (flags & FLAG_BRACE)
534 flags &= ~FLAG_BRACE;
536 array.push_back('{', LM_TC_TEX);
542 mathPrintError("Unmatching braces");
546 if (flags & FLAG_BRACE_FONT) {
547 yyvarcode = LM_TC_VAR;
548 flags &= ~FLAG_BRACE_FONT;
551 if (brace == 0 && (flags & FLAG_BRACE_LAST)) {
555 array.push_back('}', LM_TC_TEX);
559 if (flags & FLAG_BRACK_ARG) {
560 flags &= ~FLAG_BRACK_ARG;
561 unsigned char const rg = LexGetArg('[');
563 mathPrintError("Expected ']'");
568 array.push_back('[', LM_TC_CONST);
572 if (flags & FLAG_BRACK_END) {
576 array.push_back(']', LM_TC_CONST);
582 mathed_parse(ar, FLAG_BRACE_OPT | FLAG_BRACE_LAST);
583 MathScriptInset * p = lastScriptInset(array);
592 mathed_parse(ar, FLAG_BRACE_OPT | FLAG_BRACE_LAST);
593 MathScriptInset * p = lastScriptInset(array);
601 MathScriptInset * p = lastScriptInset(array);
603 p->limits(yylval.l->id ? 1 : -1);
609 if (flags & FLAG_AMPERSAND) {
610 flags &= ~FLAG_AMPERSAND;
614 lyxerr[Debug::MATHED] << "found tab unexpectedly, array: '" << array << "'\n";
620 if (flags & FLAG_NEWLINE) {
621 flags &= ~FLAG_NEWLINE;
625 lyxerr[Debug::MATHED] << "found newline unexpectedly, array: '" << array << "'\n";
631 array.push_back(new MathBigopInset(yylval.l->name, yylval.l->id));
636 if (yylval.l->id < 256) {
637 MathTextCodes tc = MathIsBOPS(yylval.l->id) ? LM_TC_BOPS: LM_TC_SYMB;
638 array.push_back(yylval.l->id, tc);
640 array.push_back(new MathFuncInset(yylval.l->name));
644 array.push_back(yylval.i, LM_TC_BOP);
649 array.push_back(new MathSpaceInset(yylval.i));
653 array.push_back(new MathDotsInset(yylval.l->name, yylval.l->id));
657 handle_frac(array, "atop");
661 handle_frac(array, "stackrel");
665 handle_frac(array, "frac");
670 unsigned char c = getuchar(yyis);
672 MathRootInset * rt = new MathRootInset;
673 mathed_parse(rt->cell(0), FLAG_BRACK_END);
674 mathed_parse(rt->cell(1), FLAG_BRACE | FLAG_BRACE_LAST);
678 MathSqrtInset * sq = new MathSqrtInset;
679 mathed_parse(sq->cell(0), FLAG_BRACE | FLAG_BRACE_LAST);
690 else if (ld == LM_TK_STR || ld == LM_TK_BOP || ld == LM_TK_SPECIAL)
694 mathed_parse(ar, FLAG_RIGHT);
699 else if (rd == LM_TK_STR || rd == LM_TK_BOP || rd == LM_TK_SPECIAL)
702 MathDelimInset * dl = new MathDelimInset(ld, rd);
709 if (flags & FLAG_RIGHT) {
713 mathPrintError("Unmatched right delimiter");
718 yyvarcode = static_cast<MathTextCodes>(yylval.l->id);
719 flags |= (FLAG_BRACE | FLAG_BRACE_FONT);
724 lyxerr[Debug::MATHED] << "LM_TK_STY not implemented\n";
725 //MathArray tmp = array;
726 //MathSizeInset * p = new MathSizeInset(MathStyles(yylval.l->id));
727 //array.push_back(p);
728 //mathed_parse(p->cell(0), FLAG_BRACE_FONT);
735 MathDecorationInset * p = new MathDecorationInset(yylval.l->id);
736 mathed_parse(p->cell(0), FLAG_BRACE | FLAG_BRACE_LAST);
743 MathAccentInset * p = new MathAccentInset(yylval.l->id);
744 mathed_parse(p->cell(0), FLAG_BRACE | FLAG_BRACE_LAST);
756 // array.push_back(t, LM_TC_CONST);
758 array.push_back(new MathFuncInset(yylval.l->name));
762 array.push_back(new MathFuncInset(yylval.l->name, LM_OT_FUNCLIM));
766 if (MathMacroTable::hasTemplate(yytext)) {
767 MathMacro * m = MathMacroTable::cloneTemplate(yytext);
768 for (int i = 0; i < m->nargs(); ++i)
769 mathed_parse(m->cell(i), FLAG_BRACE_OPT | FLAG_BRACE_LAST);
771 m->Metrics(LM_ST_TEXT);
773 array.push_back(new MathFuncInset(yytext, LM_OT_UNDEF));
783 MathInsetTypes typ = latex_mathenv[i].typ;
785 if (typ == LM_OT_MATRIX) {
786 string valign = "\0";
787 unsigned char rg = LexGetArg(0);
793 string halign = yytext;
794 MathArrayInset * mm = new MathArrayInset(halign.size(), 1);
796 mm->valign(valign[0]);
799 mathed_parse_lines(mm, halign.size(), latex_mathenv[i].numbered, false);
801 //lyxerr << "read matrix " << *mm << "\n";
804 lyxerr[Debug::MATHED] << "unknow math inset " << typ << "\n";
809 array.push_back(MathMacroTable::cloneTemplate(yylval.l->name));
814 unsigned char const rg = LexGetArg('\0', true);
816 mathPrintError("Expected '{'");
818 lyxerr[Debug::MATHED] << "[" << yytext << "]" << endl;
822 //lyxerr << " setting label to " << yytext << "\n";
828 mathPrintError("Unrecognized token");
829 lyxerr[Debug::MATHED] << "[" << t << " " << yytext << "]" << endl;
832 } // end of big switch
836 lyxerr << " Math Panic, expect problems!" << endl;
837 // Search for the end command.
840 } while (t != LM_TK_END && t);
844 if (flags & FLAG_BRACE_OPT) {
845 flags &= ~FLAG_BRACE_OPT;
853 MathInset * mathed_parse(istream & is)
857 return mathed_parse();
861 MathInset * mathed_parse(LyXLex & lex)
863 yyis = &lex.getStream();
864 yylineno = lex.GetLineNo();
866 MathInset * p = mathed_parse();
868 // Update line number
869 lex.setLineNo(yylineno);
871 // reading of end_inset
874 if (lex.GetString() == "\\end_inset")
876 lyxerr[Debug::MATHED] << "InsetFormula::Read: Garbage before \\end_inset,"
877 " or missing \\end_inset!" << endl;