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_charinset.h"
34 #include "math_dotsinset.h"
35 #include "math_decorationinset.h"
36 #include "math_deliminset.h"
37 #include "math_fracinset.h"
38 #include "math_funcinset.h"
39 #include "math_funcliminset.h"
40 #include "math_macro.h"
41 #include "math_macrotable.h"
42 #include "math_macrotemplate.h"
43 #include "math_matrixinset.h"
44 #include "math_noglyphinset.h"
45 #include "math_rootinset.h"
46 #include "math_scriptinset.h"
47 #include "math_sizeinset.h"
48 #include "math_spaceinset.h"
49 #include "math_sqrtinset.h"
50 #include "math_stackrelinset.h"
51 #include "math_symbolinset.h"
53 #include "mathed/support.h"
55 #include "support/lstrings.h"
62 // These are lexical codes, not semantic
68 LexBOP, // Binary operators or relations
80 lexcode_enum lexcode[256];
85 void mathed_parse_into(MathArray & array, unsigned flags);
87 unsigned char getuchar(std::istream * is)
92 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['|'] = lexcode['.'] =
184 lexcode['?'] = LexOther;
186 lexcode['\''] = lexcode['@'] = LexAlpha;
188 lexcode['['] = lexcode[']'] = lexcode['^'] = lexcode['_'] =
189 lexcode['&'] = LexSelf;
191 lexcode['\\'] = LexESC;
192 lexcode['{'] = LexOpen;
193 lexcode['}'] = LexClose;
197 string lexArg(unsigned char lf, bool accept_spaces = false)
201 while (yyis->good()) {
212 unsigned char rg = 0;
213 if (lf == '{') rg = '}';
214 if (lf == '[') rg = ']';
215 if (lf == '(') rg = ')';
217 lyxerr[Debug::MATHED] << "Math parse error: unknown bracket '"
218 << lf << "'" << endl;
224 unsigned char c = getuchar(yyis);
229 if ((!isspace(c) || (c == ' ' && accept_spaces)) && depth > 0)
231 } while (depth > 0 && yyis->good());
239 static bool init_done = false;
246 while (yyis->good()) {
247 unsigned char c = getuchar(yyis);
248 //lyxerr << "reading byte: '" << c << "' code: " << lexcode[c] << endl;
250 if (lexcode[c] == LexNewLine) {
253 } else if (lexcode[c] == LexComment) {
256 } while (c != '\n' && yyis->good()); // eat comments
257 } else if (lexcode[c] == LexDigit || lexcode[c] == LexOther) {
260 } else if (lexcode[c] == LexAlpha || lexcode[c] == LexSpace) {
263 } else if (lexcode[c] == LexBOP) {
266 } else if (lexcode[c] == LexMath) {
269 } else if (lexcode[c] == LexSelf) {
271 } else if (lexcode[c] == LexArgument) {
274 return LM_TK_ARGUMENT;
275 } else if (lexcode[c] == LexOpen) {
277 } else if (lexcode[c] == LexClose) {
279 } else if (lexcode[c] == LexESC) {
281 //lyxerr << "reading second byte: '" << c << "' code: " << lexcode[c] << endl;
284 latexkeys const * l = in_word_set(s);
286 //lyxerr << "found key: " << l << endl;
287 //lyxerr << "found key name: " << l->name << endl;
288 //lyxerr << "found key token: " << l->token << endl;
293 if (lexcode[c] == LexAlpha) {
295 while (lexcode[c] == LexAlpha && yyis->good()) {
299 while (lexcode[c] == LexSpace && yyis->good())
301 if (lexcode[c] != LexSpace)
304 //lyxerr[Debug::MATHED] << "reading: text '" << yytext << "'\n";
305 //lyxerr << "reading: text '" << yytext << "'\n";
306 latexkeys const * l = in_word_set(yytext);
310 if (l->token == LM_TK_BEGIN || l->token == LM_TK_END) {
311 string name = lexArg('{');
313 while (i < latex_mathenv_num && name != latex_mathenv[i].name)
316 } else if (l->token == LM_TK_SPACE)
328 MathScriptInset * prevScriptInset(MathArray const & array)
330 MathInset * p = array.back();
331 return (p && p->isScriptInset()) ? static_cast<MathScriptInset *>(p) : 0;
335 MathInset * lastScriptInset(MathArray & array, bool up, bool down, int limits)
337 MathScriptInset * p = prevScriptInset(array);
339 MathInset * b = array.back();
340 if (b && b->isScriptable()) {
341 p = new MathScriptInset(up, down, b->clone());
344 p = new MathScriptInset(up, down);
358 static bool curr_num;
359 static string curr_label;
361 void mathed_parse_lines(MathGridInset * p, int col, bool numbered, bool outmost)
363 // save global variables
364 bool const saved_num = curr_num;
365 string const saved_label = curr_label;
367 for (int row = 0; true; ++row) {
368 // reset global variables
373 int idx = p->nargs() - p->ncols();
374 for (int i = 0; i < col - 1; ++i, ++idx)
375 mathed_parse_into(p->cell(idx), FLAG_AMPERSAND);
376 mathed_parse_into(p->cell(idx), FLAG_NEWLINE | FLAG_END);
379 MathMatrixInset * m = static_cast<MathMatrixInset *>(p);
380 m->numbered(row, curr_num);
381 m->label(row, curr_label);
394 // restore global variables
395 curr_num = saved_num;
396 curr_label = saved_label;
400 MathMacroTemplate * mathed_parse_macro()
402 if (yylex() != LM_TK_NEWCOMMAND) {
403 lyxerr << "\\newcommand expected\n";
407 string name = lexArg('{').substr(1);
408 string arg = lexArg('[');
409 int narg = arg.empty() ? 0 : atoi(arg.c_str());
410 MathMacroTemplate * p = new MathMacroTemplate(name, narg);
411 mathed_parse_into(p->cell(0), FLAG_BRACE | FLAG_BRACE_LAST);
416 MathMatrixInset * mathed_parse_normal()
418 MathMatrixInset * p = 0;
425 lyxerr[Debug::MATHED]
426 << "reading math environment " << i << " "
427 << latex_mathenv[i].name << "\n";
429 MathInsetTypes typ = latex_mathenv[i].typ;
430 p = new MathMatrixInset(typ);
435 curr_num = latex_mathenv[i].numbered;
437 mathed_parse_into(p->cell(0), 0);
438 p->numbered(0, curr_num);
439 p->label(0, curr_label);
443 case LM_OT_EQUATION: {
444 curr_num = latex_mathenv[i].numbered;
446 mathed_parse_into(p->cell(0), FLAG_END);
447 p->numbered(0, curr_num);
448 p->label(0, curr_label);
452 case LM_OT_EQNARRAY: {
453 mathed_parse_lines(p, 3, latex_mathenv[i].numbered, true);
458 p->halign(lexArg('{'));
459 mathed_parse_lines(p, 2, latex_mathenv[i].numbered, true);
463 case LM_OT_ALIGNAT: {
464 p->halign(lexArg('{'));
465 mathed_parse_lines(p, 2, latex_mathenv[i].numbered, true);
470 lyxerr[Debug::MATHED]
471 << "1: unknown math environment: " << typ << "\n";
478 lyxerr[Debug::MATHED]
479 << "2 unknown math environment: " << t << "\n";
486 latexkeys const * read_delim()
489 lyxerr << "found symbol: " << ld << "\n";
490 latexkeys const * l = in_word_set(".");
497 lyxerr << "found key 1: '" << l << "'\n";
498 lyxerr << "found key 1: '" << l->name << "'\n";
504 lyxerr << "found key 2: '" << l->name << "'\n";
510 void mathed_parse_into(MathArray & array, unsigned flags)
512 static int plevel = -1;
515 MathTextCodes yyvarcode = LM_TC_VAR;
523 //lyxerr << "t: " << t << " flags: " << flags << " i: " << yylval.i
524 // << " '" << yytext << "'\n";
525 //array.dump(lyxerr);
528 if (flags & FLAG_ITEM) {
530 if (t == LM_TK_OPEN) {
531 // skip the brace and regard everything to the next matching
535 flags |= FLAG_BRACE_LAST;
537 // regard only this single token
542 if ((flags & FLAG_BRACE) && t != LM_TK_OPEN) {
544 "Expected {. Maybe you forgot to enclose an argument in {}");
552 if (!isspace(yylval.i) || yyvarcode == LM_TC_TEXTRM)
553 array.push_back(new MathCharInset(yylval.i, yyvarcode));
556 case LM_TK_ARGUMENT: {
557 MathMacroArgument * p = new MathMacroArgument(yylval.i);
564 array.push_back(new MathCharInset(yylval.i, LM_TC_SPECIAL));
568 array.push_back(new MathCharInset(yylval.i, LM_TC_CONST));
573 if (flags & FLAG_BRACE)
574 flags &= ~FLAG_BRACE;
576 array.push_back(new MathCharInset('{', LM_TC_TEX));
582 mathPrintError("Unmatching braces");
586 if (flags & FLAG_BRACE_FONT) {
587 yyvarcode = LM_TC_VAR;
588 flags &= ~FLAG_BRACE_FONT;
591 if (brace == 0 && (flags & FLAG_BRACE_LAST))
594 array.push_back(new MathCharInset('}', LM_TC_TEX));
598 array.push_back(new MathCharInset('[', LM_TC_CONST));
602 if (flags & FLAG_BRACK_END)
605 array.push_back(new MathCharInset(']', LM_TC_CONST));
610 lastScriptInset(array, true, false, limits)->cell(0), FLAG_ITEM);
615 lastScriptInset(array, false, true, limits)->cell(1), FLAG_ITEM);
619 limits = yylval.l->id;
620 //lyxerr << "setting limit to " << limits << "\n";
624 if (flags & FLAG_AMPERSAND) {
625 flags &= ~FLAG_AMPERSAND;
629 lyxerr[Debug::MATHED]
630 << "found tab unexpectedly, array: '" << array << "'\n";
634 if (flags & FLAG_NEWLINE) {
635 flags &= ~FLAG_NEWLINE;
639 lyxerr[Debug::MATHED]
640 << "found newline unexpectedly, array: '" << array << "'\n";
649 array.push_back(new MathNoglyphInset(yylval.l));
654 array.push_back(new MathBigopInset(yylval.l));
659 array.push_back(new MathFuncLimInset(yylval.l));
664 array.push_back(new MathSymbolInset(yylval.l));
668 array.push_back(new MathCharInset(yylval.i, LM_TC_BOP));
673 array.push_back(new MathSpaceInset(yylval.i));
677 array.push_back(new MathDotsInset(yylval.l));
682 MathStackrelInset * p = new MathStackrelInset;
683 mathed_parse_into(p->cell(0), FLAG_ITEM);
684 mathed_parse_into(p->cell(1), FLAG_ITEM);
691 MathFracInset * p = new MathFracInset;
692 mathed_parse_into(p->cell(0), FLAG_ITEM);
693 mathed_parse_into(p->cell(1), FLAG_ITEM);
700 unsigned char c = getuchar(yyis);
702 array.push_back(new MathRootInset);
703 mathed_parse_into(array.back()->cell(0), FLAG_BRACK_END);
704 mathed_parse_into(array.back()->cell(1), FLAG_ITEM);
707 array.push_back(new MathSqrtInset);
708 mathed_parse_into(array.back()->cell(0), FLAG_ITEM);
715 latexkeys const * l = read_delim();
717 mathed_parse_into(ar, FLAG_RIGHT);
718 latexkeys const * r = read_delim();
719 MathDelimInset * dl = new MathDelimInset(l, r);
726 if (flags & FLAG_RIGHT) {
730 mathPrintError("Unmatched right delimiter");
735 yyvarcode = static_cast<MathTextCodes>(yylval.l->id);
736 flags |= (FLAG_BRACE | FLAG_BRACE_FONT);
741 lyxerr[Debug::MATHED] << "LM_TK_STY not implemented\n";
742 //MathArray tmp = array;
743 //MathSizeInset * p = new MathSizeInset(MathStyles(yylval.l->id));
744 //array.push_back(p);
745 //mathed_parse_into(p->cell(0), FLAG_BRACE_FONT);
750 case LM_TK_DECORATION:
752 MathDecorationInset * p = new MathDecorationInset(yylval.l);
753 mathed_parse_into(p->cell(0), FLAG_ITEM);
763 array.push_back(new MathSymbolInset(yylval.l));
767 if (MathMacroTable::hasTemplate(yytext)) {
768 MathMacro * m = MathMacroTable::cloneTemplate(yytext);
769 for (int i = 0; i < m->nargs(); ++i)
770 mathed_parse_into(m->cell(i), FLAG_ITEM);
772 m->metrics(LM_ST_TEXT);
774 array.push_back(new MathFuncInset(yytext));
785 MathInsetTypes typ = latex_mathenv[i].typ;
787 if (typ == LM_OT_MATRIX) {
788 string const valign = lexArg('[') + 'c';
789 string const halign = lexArg('{');
790 //lyxerr << "valign: '" << valign << "'\n";
791 //lyxerr << "halign: '" << halign << "'\n";
792 MathArrayInset * m = new MathArrayInset(halign.size(), 1);
793 m->valign(valign[0]);
796 mathed_parse_lines(m, halign.size(), latex_mathenv[i].numbered, false);
798 //lyxerr << "read matrix " << *m << "\n";
801 lyxerr[Debug::MATHED] << "unknow math inset " << typ << "\n";
806 array.push_back(MathMacroTable::cloneTemplate(yylval.l->name));
810 curr_label = lexArg('{', true);
814 mathPrintError("Unrecognized token");
815 lyxerr[Debug::MATHED] << "[" << t << " " << yytext << "]" << endl;
818 } // end of big switch
820 if (flags & FLAG_LEAVE) {
821 flags &= ~FLAG_LEAVE;
826 lyxerr << " Math Panic, expect problems!" << endl;
827 // Search for the end command.
830 } while (yyis->good() && t != LM_TK_END && t);
841 MathArray mathed_parse_cell(string const & str)
843 istringstream is(str.c_str());
847 mathed_parse_into(ar, 0);
852 MathMacroTemplate * mathed_parse_macro(string const & str)
854 istringstream is(str.c_str());
855 return mathed_parse_macro(is);
859 MathMatrixInset * mathed_parse_normal(string const & str)
861 istringstream is(str.c_str());
862 return mathed_parse_normal(is);
867 MathMatrixInset * mathed_parse_normal(istream & is)
871 return mathed_parse_normal();
875 MathMacroTemplate * mathed_parse_macro(istream & is)
879 return mathed_parse_macro();
884 MathMatrixInset * mathed_parse_normal(LyXLex & lex)
886 yyis = &lex.getStream();
887 yylineno = lex.getLineNo();
889 MathMatrixInset * p = mathed_parse_normal();
891 // Update line number
892 lex.setLineNo(yylineno);
894 // reading of end_inset
897 if (lex.getString() == "\\end_inset")
899 lyxerr[Debug::MATHED] << "InsetFormula::Read: Garbage before \\end_inset,"
900 " or missing \\end_inset!" << endl;
906 MathMacroTemplate * mathed_parse_macro(LyXLex & lex)
908 yyis = &lex.getStream();
909 yylineno = lex.getLineNo();
911 MathMacroTemplate * p = mathed_parse_macro();
913 // Update line number
914 lex.setLineNo(yylineno);
916 // reading of end_inset
919 if (lex.getString() == "\\end_inset")
921 lyxerr[Debug::MATHED] << "InsetFormula::Read: Garbage before \\end_inset,"
922 " or missing \\end_inset!" << endl;