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_symbolinset.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"
50 #include "support/lstrings.h"
57 // These are lexical codes, not semantic
63 LexBOP, // Binary operators or relations
76 lexcode_enum lexcode[256];
79 char const * latex_special_chars = "#$%&_{}";
84 void mathed_parse_into(MathArray & array, unsigned flags);
86 unsigned char getuchar(std::istream * is)
91 lyxerr << "The input stream is not well..." << endl;
94 return static_cast<unsigned char>(c);
97 const unsigned char LM_TK_OPEN = '{';
98 const unsigned char LM_TK_CLOSE = '}';
101 FLAG_BRACE = 1 << 0, // A { needed //}
102 FLAG_BRACE_LAST = 1 << 1, // // { Last } ends the parsing process
103 FLAG_RIGHT = 1 << 2, // Next right ends the parsing process
104 FLAG_END = 1 << 3, // Next end ends the parsing process
105 FLAG_BRACE_FONT = 1 << 4, // // { Next } closes a font
106 FLAG_BRACK_END = 1 << 5, // // [ Next ] ends the parsing process
107 FLAG_AMPERSAND = 1 << 6, // Next & ends the parsing process
108 FLAG_NEWLINE = 1 << 7, // Next \\ ends the parsing process
109 FLAG_ITEM = 1 << 8, // read a (possibly braced token)
110 FLAG_LEAVE = 1 << 9, // marker for leaving the
111 FLAG_OPTARG = 1 << 10 // reads an argument in []
130 struct latex_mathenv_type {
132 char const * basename;
138 latex_mathenv_type latex_mathenv[] = {
139 {"math", "math", LM_OT_SIMPLE, 0, 0},
140 {"equation*", "equation", LM_OT_EQUATION, 0, 0},
141 {"equation", "equation", LM_OT_EQUATION, 1, 0},
142 {"eqnarray*", "eqnarray", LM_OT_EQNARRAY, 0, 0},
143 {"eqnarray", "eqnarray", LM_OT_EQNARRAY, 1, 0},
144 {"align*", "align", LM_OT_ALIGN, 0, 1},
145 {"align", "align", LM_OT_ALIGN, 1, 1},
146 {"alignat*", "alignat", LM_OT_ALIGNAT, 0, 1},
147 {"alignat", "alignat", LM_OT_ALIGNAT, 1, 1},
148 {"multline*", "multline", LM_OT_MULTLINE, 0, 1},
149 {"multline", "multline", LM_OT_MULTLINE, 1, 1},
150 {"array", "array", LM_OT_MATRIX, 0, 1}
153 int const latex_mathenv_num = sizeof(latex_mathenv)/sizeof(latex_mathenv[0]);
157 void mathPrintError(string const & msg)
159 //lyxerr[Debug::MATHED] << "Line ~" << yylineno << ": Math parse error: " << msg << endl;
160 lyxerr << "Line ~" << yylineno << ": Math parse error: " << msg << endl;
166 for (int i = 0; i <= 255; ++i) {
168 lexcode[i] = LexDigit;
170 lexcode[i] = LexSpace;
172 lexcode[i] = LexAlpha;
175 lexcode['\t'] = lexcode['\f'] = lexcode[' '] = LexSpace;
176 lexcode['\n'] = LexNewLine;
177 lexcode['%'] = LexComment;
178 lexcode['#'] = LexArgument;
179 lexcode['$'] = LexMath;
180 lexcode['+'] = lexcode['-'] = lexcode['*'] = lexcode['/']
181 = lexcode['<'] = lexcode['>'] = lexcode['='] = LexBOP;
183 lexcode['!'] = lexcode[','] = lexcode[':']
184 = lexcode[';'] = LexMathSpace;
186 lexcode['('] = lexcode[')'] = lexcode['|'] = lexcode['.'] =
187 lexcode['?'] = LexOther;
189 lexcode['\''] = lexcode['@'] = LexAlpha;
191 lexcode['['] = lexcode[']'] = lexcode['^'] = lexcode['_'] =
192 lexcode['&'] = LexSelf;
194 lexcode['\\'] = LexESC;
195 lexcode['{'] = LexOpen;
196 lexcode['}'] = LexClose;
200 string lexArg(unsigned char lf, bool accept_spaces = false)
204 while (yyis->good()) {
215 unsigned char rg = 0;
216 if (lf == '{') rg = '}';
217 if (lf == '[') rg = ']';
218 if (lf == '(') rg = ')';
220 lyxerr[Debug::MATHED] << "Math parse error: unknown bracket '"
221 << lf << "'" << endl;
227 unsigned char c = getuchar(yyis);
232 if ((!isspace(c) || (c == ' ' && accept_spaces)) && depth > 0)
234 } while (depth > 0 && yyis->good());
242 static bool init_done = false;
249 while (yyis->good()) {
250 unsigned char c = getuchar(yyis);
251 //lyxerr << "reading byte: '" << c << "' code: " << lexcode[c] << endl;
253 if (lexcode[c] == LexNewLine) {
256 } else if (lexcode[c] == LexComment) {
259 } while (c != '\n' && yyis->good()); // eat comments
260 } else if (lexcode[c] == LexDigit
261 || lexcode[c] == LexOther
262 || lexcode[c] == LexMathSpace) {
265 } else if (lexcode[c] == LexAlpha || lexcode[c] == LexSpace) {
268 } else if (lexcode[c] == LexBOP) {
271 } else if (lexcode[c] == LexMath) {
274 } else if (lexcode[c] == LexSelf) {
276 } else if (lexcode[c] == LexArgument) {
279 return LM_TK_ARGUMENT;
280 } else if (lexcode[c] == LexOpen) {
282 } else if (lexcode[c] == LexClose) {
284 } else if (lexcode[c] == LexESC) {
288 return LM_TK_NEWLINE;
291 yylval.i = LM_OT_SIMPLE;
295 yylval.i = LM_OT_SIMPLE;
299 yylval.i = LM_OT_EQUATION;
303 yylval.i = LM_OT_EQUATION;
310 if (contains(latex_special_chars, c)) {
312 return LM_TK_SPECIAL;
314 if (lexcode[c] == LexMathSpace) {
316 for (i = 0; i < 4 && static_cast<int>(c) != latex_mathspace[i][0]; ++i)
318 yylval.i = (i < 4) ? i : 0;
321 if (lexcode[c] == LexAlpha) {
323 while (lexcode[c] == LexAlpha && yyis->good()) {
327 while (lexcode[c] == LexSpace && yyis->good())
329 if (yyis->good() && lexcode[c] != LexSpace)
332 //lyxerr[Debug::MATHED] << "reading: text '" << yytext << "'\n";
333 latexkeys const * l = in_word_set(yytext);
337 if (l->token == LM_TK_BEGIN || l->token == LM_TK_END) {
338 string name = lexArg('{');
340 while (i < latex_mathenv_num && name != latex_mathenv[i].name)
343 } else if (l->token == LM_TK_SPACE)
355 MathScriptInset * prevScriptInset(MathArray const & array)
357 MathInset * p = array.back_inset();
358 return (p && p->isScriptInset()) ? static_cast<MathScriptInset *>(p) : 0;
362 MathInset * lastScriptInset(MathArray & array, bool up, bool down, int limits)
364 MathScriptInset * p = prevScriptInset(array);
366 MathInset * b = array.back_inset();
367 if (b && b->isScriptable()) {
368 p = new MathScriptInset(up, down, b->clone());
371 p = new MathScriptInset(up, down);
385 static bool curr_num;
386 static string curr_label;
388 void mathed_parse_lines(MathInset * inset, int col,
389 bool numbered, bool outmost)
391 // save global variables
392 bool const saved_num = curr_num;
393 string const saved_label = curr_label;
395 MathGridInset * p = static_cast<MathGridInset *>(inset);
396 for (int row = 0; true; ++row) {
397 // reset global variables
402 int idx = p->nargs() - p->ncols();
403 for (int i = 0; i < col - 1; ++i, ++idx)
404 mathed_parse_into(p->cell(idx), FLAG_AMPERSAND);
405 mathed_parse_into(p->cell(idx), FLAG_NEWLINE | FLAG_END);
408 MathMatrixInset * m = static_cast<MathMatrixInset *>(p);
409 m->numbered(row, curr_num);
410 m->label(row, curr_label);
421 // restore global variables
422 curr_num = saved_num;
423 curr_label = saved_label;
427 MathMacroTemplate * mathed_parse_macro()
429 if (yylex() != LM_TK_NEWCOMMAND) {
430 lyxerr << "\\newcommand expected\n";
434 string name = lexArg('{').substr(1);
435 string arg = lexArg('[');
436 int narg = arg.empty() ? 0 : atoi(arg.c_str());
437 MathMacroTemplate * p = new MathMacroTemplate(name, narg);
438 mathed_parse_into(p->cell(0), FLAG_BRACE | FLAG_BRACE_LAST);
443 MathMatrixInset * mathed_parse_normal()
445 MathMatrixInset * p = 0;
452 lyxerr[Debug::MATHED]
453 << "reading math environment " << i << " "
454 << latex_mathenv[i].name << "\n";
456 MathInsetTypes typ = latex_mathenv[i].typ;
457 p = new MathMatrixInset(typ);
458 MathMatrixInset * m = static_cast<MathMatrixInset *>(p);
462 curr_num = latex_mathenv[i].numbered;
464 mathed_parse_into(m->cell(0), 0);
465 m->numbered(0, curr_num);
466 m->label(0, curr_label);
470 case LM_OT_EQUATION: {
471 curr_num = latex_mathenv[i].numbered;
473 mathed_parse_into(m->cell(0), FLAG_END);
474 m->numbered(0, curr_num);
475 m->label(0, curr_label);
479 case LM_OT_EQNARRAY: {
480 mathed_parse_lines(m, 3, latex_mathenv[i].numbered, true);
485 m->halign(lexArg('{'));
486 mathed_parse_lines(m, 2, latex_mathenv[i].numbered, true);
490 case LM_OT_ALIGNAT: {
491 m->halign(lexArg('{'));
492 mathed_parse_lines(m, 2, latex_mathenv[i].numbered, true);
497 lyxerr[Debug::MATHED]
498 << "1: unknown math environment: " << typ << "\n";
501 p->setName(latex_mathenv[i].basename);
507 lyxerr[Debug::MATHED]
508 << "2 unknown math environment: " << t << "\n";
515 void handle_frac(MathArray & array, string const & name)
517 MathFracInset * p = new MathFracInset(name);
518 mathed_parse_into(p->cell(0), FLAG_ITEM);
519 mathed_parse_into(p->cell(1), FLAG_ITEM);
524 void mathed_parse_into(MathArray & array, unsigned flags)
526 static int plevel = -1;
529 MathTextCodes yyvarcode = LM_TC_VAR;
537 //lyxerr << "t: " << t << " flags: " << flags << " i: " << yylval.i
538 // << " '" << yytext << "'\n";
539 //array.dump(lyxerr);
542 if (flags & FLAG_ITEM) {
544 if (t == LM_TK_OPEN) {
545 // skip the brace and regard everything to the next matching
549 flags |= FLAG_BRACE_LAST;
551 // regard only this single token
556 if ((flags & FLAG_BRACE) && t != LM_TK_OPEN) {
558 "Expected {. Maybe you forgot to enclose an argument in {}");
566 if (!isspace(yylval.i) || yyvarcode == LM_TC_TEXTRM)
567 array.push_back(yylval.i, yyvarcode);
570 case LM_TK_ARGUMENT: {
571 MathMacroArgument * p = new MathMacroArgument(yylval.i);
578 array.push_back(yylval.i, LM_TC_SPECIAL);
582 array.push_back(yylval.i, LM_TC_CONST);
587 if (flags & FLAG_BRACE)
588 flags &= ~FLAG_BRACE;
590 array.push_back('{', LM_TC_TEX);
596 mathPrintError("Unmatching braces");
600 if (flags & FLAG_BRACE_FONT) {
601 yyvarcode = LM_TC_VAR;
602 flags &= ~FLAG_BRACE_FONT;
605 if (brace == 0 && (flags & FLAG_BRACE_LAST))
608 array.push_back('}', LM_TC_TEX);
612 array.push_back('[', LM_TC_CONST);
616 if (flags & FLAG_BRACK_END)
619 array.push_back(']', LM_TC_CONST);
624 lastScriptInset(array, true, false, limits)->cell(0), FLAG_ITEM);
629 lastScriptInset(array, false, true, limits)->cell(1), FLAG_ITEM);
633 limits = yylval.l->id;
634 //lyxerr << "setting limit to " << limits << "\n";
638 if (flags & FLAG_AMPERSAND) {
639 flags &= ~FLAG_AMPERSAND;
643 lyxerr[Debug::MATHED]
644 << "found tab unexpectedly, array: '" << array << "'\n";
648 if (flags & FLAG_NEWLINE) {
649 flags &= ~FLAG_NEWLINE;
653 lyxerr[Debug::MATHED]
654 << "found newline unexpectedly, array: '" << array << "'\n";
664 array.push_back(new MathSymbolInset(yylval.l));
668 array.push_back(yylval.i, LM_TC_BOP);
673 array.push_back(new MathSpaceInset(yylval.i));
677 array.push_back(new MathDotsInset(yylval.l));
681 handle_frac(array, "atop");
685 handle_frac(array, "stackrel");
689 handle_frac(array, "frac");
694 unsigned char c = getuchar(yyis);
696 array.push_back(new MathRootInset);
697 mathed_parse_into(array.back_inset()->cell(0), FLAG_BRACK_END);
698 mathed_parse_into(array.back_inset()->cell(1), FLAG_ITEM);
701 array.push_back(new MathSqrtInset);
702 mathed_parse_into(array.back_inset()->cell(0), FLAG_ITEM);
712 else if (ld == LM_TK_STR || ld == LM_TK_BOP || ld == LM_TK_SPECIAL)
716 mathed_parse_into(ar, FLAG_RIGHT);
721 else if (rd == LM_TK_STR || rd == LM_TK_BOP || rd == LM_TK_SPECIAL)
724 MathDelimInset * dl = new MathDelimInset(ld, rd);
731 if (flags & FLAG_RIGHT) {
735 mathPrintError("Unmatched right delimiter");
740 yyvarcode = static_cast<MathTextCodes>(yylval.l->id);
741 flags |= (FLAG_BRACE | FLAG_BRACE_FONT);
746 lyxerr[Debug::MATHED] << "LM_TK_STY not implemented\n";
747 //MathArray tmp = array;
748 //MathSizeInset * p = new MathSizeInset(MathStyles(yylval.l->id));
749 //array.push_back(p);
750 //mathed_parse_into(p->cell(0), FLAG_BRACE_FONT);
755 case LM_TK_DECORATION:
757 MathDecorationInset * p = new MathDecorationInset(yylval.l);
758 mathed_parse_into(p->cell(0), FLAG_ITEM);
768 array.push_back(new MathSymbolInset(yylval.l));
772 if (MathMacroTable::hasTemplate(yytext)) {
773 MathMacro * m = MathMacroTable::cloneTemplate(yytext);
774 for (int i = 0; i < m->nargs(); ++i)
775 mathed_parse_into(m->cell(i), FLAG_ITEM);
777 m->metrics(LM_ST_TEXT);
779 array.push_back(new MathFuncInset(yytext));
790 MathInsetTypes typ = latex_mathenv[i].typ;
792 if (typ == LM_OT_MATRIX) {
793 string const valign = lexArg('[') + 'c';
794 string const halign = lexArg('{');
795 //lyxerr << "valign: '" << valign << "'\n";
796 //lyxerr << "halign: '" << halign << "'\n";
797 MathArrayInset * m = new MathArrayInset(halign.size(), 1);
798 m->valign(valign[0]);
801 mathed_parse_lines(m, halign.size(), latex_mathenv[i].numbered, false);
803 //lyxerr << "read matrix " << *m << "\n";
806 lyxerr[Debug::MATHED] << "unknow math inset " << typ << "\n";
811 array.push_back(MathMacroTable::cloneTemplate(yylval.l->name));
815 curr_label = lexArg('{', true);
819 mathPrintError("Unrecognized token");
820 lyxerr[Debug::MATHED] << "[" << t << " " << yytext << "]" << endl;
823 } // end of big switch
825 if (flags & FLAG_LEAVE) {
826 flags &= ~FLAG_LEAVE;
831 lyxerr << " Math Panic, expect problems!" << endl;
832 // Search for the end command.
835 } while (yyis->good() && t != LM_TK_END && t);
846 MathArray mathed_parse_cell(string const & str)
848 istringstream is(str.c_str());
852 mathed_parse_into(ar, 0);
857 MathMacroTemplate * mathed_parse_macro(string const & str)
859 istringstream is(str.c_str());
860 return mathed_parse_macro(is);
864 MathMatrixInset * mathed_parse_normal(string const & str)
866 istringstream is(str.c_str());
867 return mathed_parse_normal(is);
872 MathMatrixInset * mathed_parse_normal(istream & is)
876 return mathed_parse_normal();
880 MathMacroTemplate * mathed_parse_macro(istream & is)
884 return mathed_parse_macro();
889 MathMatrixInset * mathed_parse_normal(LyXLex & lex)
891 yyis = &lex.getStream();
892 yylineno = lex.GetLineNo();
894 MathMatrixInset * p = mathed_parse_normal();
896 // Update line number
897 lex.setLineNo(yylineno);
899 // reading of end_inset
902 if (lex.GetString() == "\\end_inset")
904 lyxerr[Debug::MATHED] << "InsetFormula::Read: Garbage before \\end_inset,"
905 " or missing \\end_inset!" << endl;
911 MathMacroTemplate * mathed_parse_macro(LyXLex & lex)
913 yyis = &lex.getStream();
914 yylineno = lex.GetLineNo();
916 MathMacroTemplate * p = mathed_parse_macro();
918 // Update line number
919 lex.setLineNo(yylineno);
921 // reading of end_inset
924 if (lex.GetString() == "\\end_inset")
926 lyxerr[Debug::MATHED] << "InsetFormula::Read: Garbage before \\end_inset,"
927 " or missing \\end_inset!" << endl;