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.
25 #pragma implementation
28 #include "math_parser.h"
30 #include "math_inset.h"
31 #include "math_arrayinset.h"
32 #include "math_bigopinset.h"
33 #include "math_dotsinset.h"
34 #include "math_decorationinset.h"
35 #include "math_deliminset.h"
36 #include "math_fracinset.h"
37 #include "math_funcinset.h"
38 #include "math_macro.h"
39 #include "math_macrotable.h"
40 #include "math_macrotemplate.h"
41 #include "math_matrixinset.h"
42 #include "math_rootinset.h"
43 #include "math_scriptinset.h"
44 #include "math_sizeinset.h"
45 #include "math_spaceinset.h"
46 #include "math_sqrtinset.h"
48 #include "mathed/support.h"
56 // These are lexical codes, not semantic
62 LexBOP, // Binary operators or relations
75 lexcode_enum lexcode[256];
78 char const * latex_special_chars = "#$%&_{}";
83 void mathed_parse(MathArray & array, unsigned flags);
85 unsigned char getuchar(std::istream * is)
89 return static_cast<unsigned char>(c);
92 const unsigned char LM_TK_OPEN = '{';
93 const unsigned char LM_TK_CLOSE = '}';
96 FLAG_BRACE = 1 << 0, // A { needed //}
97 FLAG_BRACE_LAST = 1 << 1, // // { Last } ends the parsing process
98 FLAG_RIGHT = 1 << 2, // Next right ends the parsing process
99 FLAG_END = 1 << 3, // Next end ends the parsing process
100 FLAG_BRACE_FONT = 1 << 4, // // { Next } closes a font
101 FLAG_BRACK_END = 1 << 5, // // [ Next ] ends the parsing process
102 FLAG_AMPERSAND = 1 << 6, // Next & ends the parsing process
103 FLAG_NEWLINE = 1 << 7, // Next \\ ends the parsing process
104 FLAG_ITEM = 1 << 8, // read a (possibly braced token)
105 FLAG_LEAVE = 1 << 9, // marker for leaving the
106 FLAG_OPTARG = 1 << 10 // reads an argument in []
122 MathTextCodes yyvarcode;
126 struct latex_mathenv_type {
128 char const * basename;
134 latex_mathenv_type latex_mathenv[] = {
135 {"math", "math", LM_OT_SIMPLE, 0, 0},
136 {"equation*", "equation", LM_OT_EQUATION, 0, 0},
137 {"equation", "equation", LM_OT_EQUATION, 1, 0},
138 {"eqnarray*", "eqnarray", LM_OT_EQNARRAY, 0, 0},
139 {"eqnarray", "eqnarray", LM_OT_EQNARRAY, 1, 0},
140 {"align*", "align", LM_OT_ALIGN, 0, 1},
141 {"align", "align", LM_OT_ALIGN, 1, 1},
142 {"alignat*", "alignat", LM_OT_ALIGNAT, 0, 1},
143 {"alignat", "alignat", LM_OT_ALIGNAT, 1, 1},
144 {"multline*", "multline", LM_OT_MULTLINE, 0, 1},
145 {"multline", "multline", LM_OT_MULTLINE, 1, 1},
146 {"array", "array", LM_OT_MATRIX, 0, 1}
149 int const latex_mathenv_num = sizeof(latex_mathenv)/sizeof(latex_mathenv[0]);
153 void mathPrintError(string const & msg)
155 //lyxerr[Debug::MATHED] << "Line ~" << yylineno << ": Math parse error: " << msg << endl;
156 lyxerr << "Line ~" << yylineno << ": Math parse error: " << msg << endl;
162 for (int i = 0; i <= 255; ++i) {
164 lexcode[i] = LexDigit;
166 lexcode[i] = LexSpace;
168 lexcode[i] = LexAlpha;
171 lexcode['\t'] = lexcode['\f'] = lexcode[' '] = LexSpace;
172 lexcode['\n'] = LexNewLine;
173 lexcode['%'] = LexComment;
174 lexcode['#'] = LexArgument;
175 lexcode['$'] = LexMath;
176 lexcode['+'] = lexcode['-'] = lexcode['*'] = lexcode['/']
177 = lexcode['<'] = lexcode['>'] = lexcode['='] = LexBOP;
179 lexcode['!'] = lexcode[','] = lexcode[':']
180 = lexcode[';'] = LexMathSpace;
182 lexcode['('] = lexcode[')'] = lexcode['|'] = lexcode['.'] =
183 lexcode['?'] = LexOther;
185 lexcode['\''] = lexcode['@'] = LexAlpha;
187 lexcode['['] = lexcode[']'] = lexcode['^'] = lexcode['_'] =
188 lexcode['&'] = LexSelf;
190 lexcode['\\'] = LexESC;
191 lexcode['{'] = LexOpen;
192 lexcode['}'] = LexClose;
196 string lexArg(unsigned char lf, bool accept_spaces = false)
200 while (yyis->good()) {
211 unsigned char rg = 0;
212 if (lf == '{') rg = '}';
213 if (lf == '[') rg = ']';
214 if (lf == '(') rg = ')';
216 lyxerr[Debug::MATHED] << "Math parse error: unknown bracket '"
217 << lf << "'" << endl;
223 unsigned char c = getuchar(yyis);
228 if ((!isspace(c) || (c == ' ' && accept_spaces)) && depth > 0)
230 } while (depth > 0 && yyis->good());
238 static bool init_done = false;
245 while (yyis->good()) {
246 unsigned char c = getuchar(yyis);
247 //lyxerr << "reading byte: '" << c << "' code: " << lexcode[c] << endl;
249 if (yyvarcode == LM_TC_TEXTRM && c == ' ') {
252 } else if (lexcode[c] == LexNewLine) {
255 } else if (lexcode[c] == LexComment) {
258 } while (c != '\n' && yyis->good()); // eat comments
259 } else if (lexcode[c] == LexDigit
260 || lexcode[c] == LexOther
261 || lexcode[c] == LexMathSpace) {
264 } else if (lexcode[c] == LexAlpha) {
267 } else if (lexcode[c] == LexBOP) {
270 } else if (lexcode[c] == LexMath) {
273 } else if (lexcode[c] == LexSelf) {
275 } else if (lexcode[c] == LexArgument) {
278 return LM_TK_ARGUMENT;
279 } else if (lexcode[c] == LexOpen) {
281 } else if (lexcode[c] == LexClose) {
283 } else if (lexcode[c] == LexESC) {
287 return LM_TK_NEWLINE;
290 yylval.i = LM_OT_SIMPLE;
294 yylval.i = LM_OT_SIMPLE;
298 yylval.i = LM_OT_EQUATION;
302 yylval.i = LM_OT_EQUATION;
305 if (contains(latex_special_chars, c)) {
307 return LM_TK_SPECIAL;
309 if (lexcode[c] == LexMathSpace) {
311 for (i = 0; i < 4 && static_cast<int>(c) != latex_mathspace[i][0]; ++i)
313 yylval.i = (i < 4) ? i : 0;
316 if (lexcode[c] == LexAlpha) {
318 while (lexcode[c] == LexAlpha && yyis->good()) {
324 //lyxerr[Debug::MATHED] << "reading: text '" << yytext << "'\n";
325 latexkeys const * l = in_word_set(yytext);
329 if (l->token == LM_TK_BEGIN || l->token == LM_TK_END) {
330 string name = lexArg('{');
332 while (i < latex_mathenv_num && name != latex_mathenv[i].name)
335 } else if (l->token == LM_TK_SPACE)
348 MathScriptInset * prevScriptInset(MathArray const & array)
350 MathInset * p = array.back_inset();
351 return (p && p->isScriptInset()) ? static_cast<MathScriptInset *>(p) : 0;
355 MathInset * lastScriptInset(MathArray & array, bool up, bool down, int limits)
357 MathScriptInset * p = prevScriptInset(array);
359 MathInset * b = array.back_inset();
360 if (b && b->isScriptable()) {
361 p = new MathScriptInset(up, down, b->clone());
364 p = new MathScriptInset(up, down);
379 static bool curr_num;
380 static string curr_label;
382 void mathed_parse_lines(MathInset * inset, int col, bool numbered, bool outmost)
384 // save global variables
385 bool saved_num = curr_num;
386 string saved_label = curr_label;
388 MathGridInset * p = static_cast<MathGridInset *>(inset);
389 for (int row = 0; true; ++row) {
390 // reset global variables
392 curr_label = string();
395 int idx = p->nargs() - p->ncols();
396 for (int i = 0; i < col - 1; ++i, ++idx)
397 mathed_parse(p->cell(idx), FLAG_AMPERSAND);
398 mathed_parse(p->cell(idx), FLAG_NEWLINE | FLAG_END);
401 MathMatrixInset * m = static_cast<MathMatrixInset *>(p);
402 m->numbered(row, curr_num);
403 m->label(row, curr_label);
414 // restore global variables
415 curr_num = saved_num;
416 curr_label = saved_label;
420 MathInset * mathed_parse()
426 case LM_TK_NEWCOMMAND: {
427 string name = lexArg('{').substr(1);
428 string arg = lexArg('[');
429 int narg = arg.empty() ? 0 : atoi(arg.c_str());
430 p = new MathMacroTemplate(name, narg);
431 mathed_parse(p->cell(0), FLAG_BRACE | FLAG_BRACE_LAST);
432 //lyxerr[Debug::MATHED] << "LM_TK_NEWCOMMAND: name: "
433 // << name << " nargs: " << narg << "\n";
440 lyxerr[Debug::MATHED]
441 << "reading math environment " << i << " "
442 << latex_mathenv[i].name << "\n";
444 MathInsetTypes typ = latex_mathenv[i].typ;
445 p = new MathMatrixInset(typ);
446 MathMatrixInset * m = static_cast<MathMatrixInset *>(p);
450 curr_num = latex_mathenv[i].numbered;
451 curr_label = string();
452 mathed_parse(m->cell(0), 0);
453 m->numbered(0, curr_num);
454 m->label(0, curr_label);
458 case LM_OT_EQUATION: {
459 curr_num = latex_mathenv[i].numbered;
460 curr_label = string();
461 mathed_parse(m->cell(0), FLAG_END);
462 m->numbered(0, curr_num);
463 m->label(0, curr_label);
467 case LM_OT_EQNARRAY: {
468 mathed_parse_lines(m, 3, latex_mathenv[i].numbered, true);
473 m->halign(lexArg('{'));
474 mathed_parse_lines(m, 2, latex_mathenv[i].numbered, true);
478 case LM_OT_ALIGNAT: {
479 m->halign(lexArg('{'));
480 mathed_parse_lines(m, 2, latex_mathenv[i].numbered, true);
485 lyxerr[Debug::MATHED]
486 << "1: unknown math environment: " << typ << "\n";
489 p->setName(latex_mathenv[i].basename);
495 lyxerr[Debug::MATHED]
496 << "2 unknown math environment: " << t << "\n";
503 void handle_frac(MathArray & array, string const & name)
505 MathFracInset * p = new MathFracInset(name);
506 mathed_parse(p->cell(0), FLAG_ITEM);
507 mathed_parse(p->cell(1), FLAG_ITEM);
512 void mathed_parse(MathArray & array, unsigned flags)
516 static int plevel = -1;
517 yyvarcode = LM_TC_VAR;
524 //lyxerr << "t: " << t << " flags: " << flags << " i: " << yylval.i << "\n";
525 // << " plevel: " << plevel << " ";
526 //array.dump(lyxerr);
529 if (flags & FLAG_ITEM) {
531 if (t == LM_TK_OPEN) {
532 // skip the brace and regard everything to the next matching
536 flags |= FLAG_BRACE_LAST;
538 // regard only this single token
543 if ((flags & FLAG_BRACE) && t != LM_TK_OPEN) {
545 "Expected {. Maybe you forgot to enclose an argument in {}");
553 array.push_back(yylval.i, yyvarcode);
557 array.push_back(new MathMacroArgument(yylval.i));
561 array.push_back(yylval.i, LM_TC_SPECIAL);
565 array.push_back(yylval.i, LM_TC_CONST);
570 if (flags & FLAG_BRACE)
571 flags &= ~FLAG_BRACE;
573 array.push_back('{', LM_TC_TEX);
579 mathPrintError("Unmatching braces");
583 if (flags & FLAG_BRACE_FONT) {
584 yyvarcode = LM_TC_VAR;
585 flags &= ~FLAG_BRACE_FONT;
588 if (brace == 0 && (flags & FLAG_BRACE_LAST))
591 array.push_back('}', LM_TC_TEX);
595 array.push_back('[', LM_TC_CONST);
599 if (flags & FLAG_BRACK_END)
602 array.push_back(']', LM_TC_CONST);
607 lastScriptInset(array, true, false, limits)->cell(0), FLAG_ITEM);
612 lastScriptInset(array, false, true, limits)->cell(1), FLAG_ITEM);
616 limits = yylval.l->id;
617 //lyxerr << "setting limit to " << limits << "\n";
621 if (flags & FLAG_AMPERSAND) {
622 flags &= ~FLAG_AMPERSAND;
626 lyxerr[Debug::MATHED]
627 << "found tab unexpectedly, array: '" << array << "'\n";
631 if (flags & FLAG_NEWLINE) {
632 flags &= ~FLAG_NEWLINE;
636 lyxerr[Debug::MATHED]
637 << "found newline unexpectedly, array: '" << array << "'\n";
647 array.push_back(new MathBigopInset(yylval.l));
651 array.push_back(yylval.i, LM_TC_BOP);
656 array.push_back(new MathSpaceInset(yylval.i));
660 array.push_back(new MathDotsInset(yylval.l));
664 handle_frac(array, "atop");
668 handle_frac(array, "stackrel");
672 handle_frac(array, "frac");
677 unsigned char c = getuchar(yyis);
679 array.push_back(new MathRootInset);
680 mathed_parse(array.back_inset()->cell(0), FLAG_BRACK_END);
681 mathed_parse(array.back_inset()->cell(1), FLAG_ITEM);
684 array.push_back(new MathSqrtInset);
685 mathed_parse(array.back_inset()->cell(0), FLAG_ITEM);
695 else if (ld == LM_TK_STR || ld == LM_TK_BOP || ld == LM_TK_SPECIAL)
699 mathed_parse(ar, FLAG_RIGHT);
704 else if (rd == LM_TK_STR || rd == LM_TK_BOP || rd == LM_TK_SPECIAL)
707 MathDelimInset * dl = new MathDelimInset(ld, rd);
714 if (flags & FLAG_RIGHT) {
718 mathPrintError("Unmatched right delimiter");
723 yyvarcode = static_cast<MathTextCodes>(yylval.l->id);
724 flags |= (FLAG_BRACE | FLAG_BRACE_FONT);
729 lyxerr[Debug::MATHED] << "LM_TK_STY not implemented\n";
730 //MathArray tmp = array;
731 //MathSizeInset * p = new MathSizeInset(MathStyles(yylval.l->id));
732 //array.push_back(p);
733 //mathed_parse(p->cell(0), FLAG_BRACE_FONT);
738 case LM_TK_DECORATION:
740 MathDecorationInset * p = new MathDecorationInset(yylval.l);
741 mathed_parse(p->cell(0), FLAG_ITEM);
751 array.push_back(new MathFuncInset(yylval.l->name));
755 if (MathMacroTable::hasTemplate(yytext)) {
756 MathMacro * m = MathMacroTable::cloneTemplate(yytext);
757 for (int i = 0; i < m->nargs(); ++i)
758 mathed_parse(m->cell(i), FLAG_ITEM);
760 m->metrics(LM_ST_TEXT);
762 array.push_back(new MathFuncInset(yytext));
773 MathInsetTypes typ = latex_mathenv[i].typ;
775 if (typ == LM_OT_MATRIX) {
776 string valign = lexArg('[') + 'c';
777 string halign = lexArg('{');
778 //lyxerr << "valign: '" << valign << "'\n";
779 //lyxerr << "halign: '" << halign << "'\n";
780 MathArrayInset * m = new MathArrayInset(halign.size(), 1);
781 m->valign(valign[0]);
784 mathed_parse_lines(m, halign.size(), latex_mathenv[i].numbered, false);
786 //lyxerr << "read matrix " << *m << "\n";
789 lyxerr[Debug::MATHED] << "unknow math inset " << typ << "\n";
794 array.push_back(MathMacroTable::cloneTemplate(yylval.l->name));
798 curr_label = lexArg('{', true);
802 mathPrintError("Unrecognized token");
803 lyxerr[Debug::MATHED] << "[" << t << " " << yytext << "]" << endl;
806 } // end of big switch
808 if (flags & FLAG_LEAVE) {
809 flags &= ~FLAG_LEAVE;
814 lyxerr << " Math Panic, expect problems!" << endl;
815 // Search for the end command.
818 } while (yyis->good() && t != LM_TK_END && t);
829 MathArray mathed_parse_cell(string const & str)
831 istringstream is(str.c_str());
840 MathInset * mathed_parse(string const & str)
842 istringstream is(str.c_str());
843 return mathed_parse(is);
847 MathInset * mathed_parse(istream & is)
851 return mathed_parse();
855 MathInset * mathed_parse(LyXLex & lex)
857 yyis = &lex.getStream();
858 yylineno = lex.GetLineNo();
860 MathInset * p = mathed_parse();
862 // Update line number
863 lex.setLineNo(yylineno);
865 // reading of end_inset
868 if (lex.GetString() == "\\end_inset")
870 lyxerr[Debug::MATHED] << "InsetFormula::Read: Garbage before \\end_inset,"
871 " or missing \\end_inset!" << endl;