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_funcliminset.h"
39 #include "math_macro.h"
40 #include "math_macrotable.h"
41 #include "math_macrotemplate.h"
42 #include "math_matrixinset.h"
43 #include "math_rootinset.h"
44 #include "math_scriptinset.h"
45 #include "math_sizeinset.h"
46 #include "math_spaceinset.h"
47 #include "math_sqrtinset.h"
48 #include "math_symbolinset.h"
50 #include "mathed/support.h"
52 #include "support/lstrings.h"
59 // These are lexical codes, not semantic
65 LexBOP, // Binary operators or relations
78 lexcode_enum lexcode[256];
81 char const * latex_special_chars = "#$%&_{}";
86 void mathed_parse_into(MathArray & array, unsigned flags);
88 unsigned char getuchar(std::istream * is)
93 lyxerr << "The input stream is not well..." << endl;
95 return static_cast<unsigned char>(c);
98 const unsigned char LM_TK_OPEN = '{';
99 const unsigned char LM_TK_CLOSE = '}';
102 FLAG_BRACE = 1 << 0, // A { needed //}
103 FLAG_BRACE_LAST = 1 << 1, // // { Last } ends the parsing process
104 FLAG_RIGHT = 1 << 2, // Next right ends the parsing process
105 FLAG_END = 1 << 3, // Next end ends the parsing process
106 FLAG_BRACE_FONT = 1 << 4, // // { Next } closes a font
107 FLAG_BRACK_END = 1 << 5, // // [ Next ] ends the parsing process
108 FLAG_AMPERSAND = 1 << 6, // Next & ends the parsing process
109 FLAG_NEWLINE = 1 << 7, // Next \\ ends the parsing process
110 FLAG_ITEM = 1 << 8, // read a (possibly braced token)
111 FLAG_LEAVE = 1 << 9, // marker for leaving the
112 FLAG_OPTARG = 1 << 10 // reads an argument in []
131 struct latex_mathenv_type {
133 char const * basename;
139 latex_mathenv_type latex_mathenv[] = {
140 {"math", "math", LM_OT_SIMPLE, 0, 0},
141 {"equation*", "equation", LM_OT_EQUATION, 0, 0},
142 {"equation", "equation", LM_OT_EQUATION, 1, 0},
143 {"eqnarray*", "eqnarray", LM_OT_EQNARRAY, 0, 0},
144 {"eqnarray", "eqnarray", LM_OT_EQNARRAY, 1, 0},
145 {"align*", "align", LM_OT_ALIGN, 0, 1},
146 {"align", "align", LM_OT_ALIGN, 1, 1},
147 {"alignat*", "alignat", LM_OT_ALIGNAT, 0, 1},
148 {"alignat", "alignat", LM_OT_ALIGNAT, 1, 1},
149 {"multline*", "multline", LM_OT_MULTLINE, 0, 1},
150 {"multline", "multline", LM_OT_MULTLINE, 1, 1},
151 {"array", "array", LM_OT_MATRIX, 0, 1}
154 int const latex_mathenv_num = sizeof(latex_mathenv)/sizeof(latex_mathenv[0]);
158 void mathPrintError(string const & msg)
160 //lyxerr[Debug::MATHED] << "Line ~" << yylineno << ": Math parse error: " << msg << endl;
161 lyxerr << "Line ~" << yylineno << ": Math parse error: " << msg << endl;
167 for (int i = 0; i <= 255; ++i) {
169 lexcode[i] = LexDigit;
171 lexcode[i] = LexSpace;
173 lexcode[i] = LexAlpha;
176 lexcode['\t'] = lexcode['\f'] = lexcode[' '] = LexSpace;
177 lexcode['\n'] = LexNewLine;
178 lexcode['%'] = LexComment;
179 lexcode['#'] = LexArgument;
180 lexcode['$'] = LexMath;
181 lexcode['+'] = lexcode['-'] = lexcode['*'] = lexcode['/']
182 = lexcode['<'] = lexcode['>'] = lexcode['='] = LexBOP;
184 lexcode['!'] = lexcode[','] = lexcode[':']
185 = lexcode[';'] = LexMathSpace;
187 lexcode['('] = lexcode[')'] = lexcode['|'] = lexcode['.'] =
188 lexcode['?'] = LexOther;
190 lexcode['\''] = lexcode['@'] = LexAlpha;
192 lexcode['['] = lexcode[']'] = lexcode['^'] = lexcode['_'] =
193 lexcode['&'] = LexSelf;
195 lexcode['\\'] = LexESC;
196 lexcode['{'] = LexOpen;
197 lexcode['}'] = LexClose;
201 string lexArg(unsigned char lf, bool accept_spaces = false)
205 while (yyis->good()) {
216 unsigned char rg = 0;
217 if (lf == '{') rg = '}';
218 if (lf == '[') rg = ']';
219 if (lf == '(') rg = ')';
221 lyxerr[Debug::MATHED] << "Math parse error: unknown bracket '"
222 << lf << "'" << endl;
228 unsigned char c = getuchar(yyis);
233 if ((!isspace(c) || (c == ' ' && accept_spaces)) && depth > 0)
235 } while (depth > 0 && yyis->good());
243 static bool init_done = false;
250 while (yyis->good()) {
251 unsigned char c = getuchar(yyis);
252 //lyxerr << "reading byte: '" << c << "' code: " << lexcode[c] << endl;
254 if (lexcode[c] == LexNewLine) {
257 } else if (lexcode[c] == LexComment) {
260 } while (c != '\n' && yyis->good()); // eat comments
261 } else if (lexcode[c] == LexDigit
262 || lexcode[c] == LexOther
263 || lexcode[c] == LexMathSpace) {
266 } else if (lexcode[c] == LexAlpha || lexcode[c] == LexSpace) {
269 } else if (lexcode[c] == LexBOP) {
272 } else if (lexcode[c] == LexMath) {
275 } else if (lexcode[c] == LexSelf) {
277 } else if (lexcode[c] == LexArgument) {
280 return LM_TK_ARGUMENT;
281 } else if (lexcode[c] == LexOpen) {
283 } else if (lexcode[c] == LexClose) {
285 } else if (lexcode[c] == LexESC) {
289 return LM_TK_NEWLINE;
292 yylval.i = LM_OT_SIMPLE;
296 yylval.i = LM_OT_SIMPLE;
300 yylval.i = LM_OT_EQUATION;
304 yylval.i = LM_OT_EQUATION;
311 if (contains(latex_special_chars, c)) {
313 return LM_TK_SPECIAL;
315 if (lexcode[c] == LexMathSpace) {
317 for (i = 0; i < 4 && static_cast<int>(c) != latex_mathspace[i][0]; ++i)
319 yylval.i = (i < 4) ? i : 0;
322 if (lexcode[c] == LexAlpha) {
324 while (lexcode[c] == LexAlpha && yyis->good()) {
328 while (lexcode[c] == LexSpace && yyis->good())
330 if (lexcode[c] != LexSpace)
333 //lyxerr[Debug::MATHED] << "reading: text '" << yytext << "'\n";
334 latexkeys const * l = in_word_set(yytext);
338 if (l->token == LM_TK_BEGIN || l->token == LM_TK_END) {
339 string name = lexArg('{');
341 while (i < latex_mathenv_num && name != latex_mathenv[i].name)
344 } else if (l->token == LM_TK_SPACE)
356 MathScriptInset * prevScriptInset(MathArray const & array)
358 MathInset * p = array.back();
359 return (p && p->isScriptInset()) ? static_cast<MathScriptInset *>(p) : 0;
363 MathInset * lastScriptInset(MathArray & array, bool up, bool down, int limits)
365 MathScriptInset * p = prevScriptInset(array);
367 MathInset * b = array.back();
368 if (b && b->isScriptable()) {
369 p = new MathScriptInset(up, down, b->clone());
372 p = new MathScriptInset(up, down);
386 static bool curr_num;
387 static string curr_label;
389 void mathed_parse_lines(MathInset * inset, int col,
390 bool numbered, bool outmost)
392 // save global variables
393 bool const saved_num = curr_num;
394 string const saved_label = curr_label;
396 MathGridInset * p = static_cast<MathGridInset *>(inset);
397 for (int row = 0; true; ++row) {
398 // reset global variables
403 int idx = p->nargs() - p->ncols();
404 for (int i = 0; i < col - 1; ++i, ++idx)
405 mathed_parse_into(p->cell(idx), FLAG_AMPERSAND);
406 mathed_parse_into(p->cell(idx), FLAG_NEWLINE | FLAG_END);
409 MathMatrixInset * m = static_cast<MathMatrixInset *>(p);
410 m->numbered(row, curr_num);
411 m->label(row, curr_label);
422 // restore global variables
423 curr_num = saved_num;
424 curr_label = saved_label;
428 MathMacroTemplate * mathed_parse_macro()
430 if (yylex() != LM_TK_NEWCOMMAND) {
431 lyxerr << "\\newcommand expected\n";
435 string name = lexArg('{').substr(1);
436 string arg = lexArg('[');
437 int narg = arg.empty() ? 0 : atoi(arg.c_str());
438 MathMacroTemplate * p = new MathMacroTemplate(name, narg);
439 mathed_parse_into(p->cell(0), FLAG_BRACE | FLAG_BRACE_LAST);
444 MathMatrixInset * mathed_parse_normal()
446 MathMatrixInset * p = 0;
453 lyxerr[Debug::MATHED]
454 << "reading math environment " << i << " "
455 << latex_mathenv[i].name << "\n";
457 MathInsetTypes typ = latex_mathenv[i].typ;
458 p = new MathMatrixInset(typ);
459 MathMatrixInset * m = static_cast<MathMatrixInset *>(p);
463 curr_num = latex_mathenv[i].numbered;
465 mathed_parse_into(m->cell(0), 0);
466 m->numbered(0, curr_num);
467 m->label(0, curr_label);
471 case LM_OT_EQUATION: {
472 curr_num = latex_mathenv[i].numbered;
474 mathed_parse_into(m->cell(0), FLAG_END);
475 m->numbered(0, curr_num);
476 m->label(0, curr_label);
480 case LM_OT_EQNARRAY: {
481 mathed_parse_lines(m, 3, latex_mathenv[i].numbered, true);
486 m->halign(lexArg('{'));
487 mathed_parse_lines(m, 2, latex_mathenv[i].numbered, true);
491 case LM_OT_ALIGNAT: {
492 m->halign(lexArg('{'));
493 mathed_parse_lines(m, 2, latex_mathenv[i].numbered, true);
498 lyxerr[Debug::MATHED]
499 << "1: unknown math environment: " << typ << "\n";
502 p->setName(latex_mathenv[i].basename);
508 lyxerr[Debug::MATHED]
509 << "2 unknown math environment: " << t << "\n";
516 void handle_frac(MathArray & array, string const & name)
518 MathFracInset * p = new MathFracInset(name);
519 mathed_parse_into(p->cell(0), FLAG_ITEM);
520 mathed_parse_into(p->cell(1), FLAG_ITEM);
525 void mathed_parse_into(MathArray & array, unsigned flags)
527 static int plevel = -1;
530 MathTextCodes yyvarcode = LM_TC_VAR;
538 //lyxerr << "t: " << t << " flags: " << flags << " i: " << yylval.i
539 // << " '" << yytext << "'\n";
540 //array.dump(lyxerr);
543 if (flags & FLAG_ITEM) {
545 if (t == LM_TK_OPEN) {
546 // skip the brace and regard everything to the next matching
550 flags |= FLAG_BRACE_LAST;
552 // regard only this single token
557 if ((flags & FLAG_BRACE) && t != LM_TK_OPEN) {
559 "Expected {. Maybe you forgot to enclose an argument in {}");
567 if (!isspace(yylval.i) || yyvarcode == LM_TC_TEXTRM)
568 array.push_back(yylval.i, yyvarcode);
571 case LM_TK_ARGUMENT: {
572 MathMacroArgument * p = new MathMacroArgument(yylval.i);
579 array.push_back(yylval.i, LM_TC_SPECIAL);
583 array.push_back(yylval.i, LM_TC_CONST);
588 if (flags & FLAG_BRACE)
589 flags &= ~FLAG_BRACE;
591 array.push_back('{', LM_TC_TEX);
597 mathPrintError("Unmatching braces");
601 if (flags & FLAG_BRACE_FONT) {
602 yyvarcode = LM_TC_VAR;
603 flags &= ~FLAG_BRACE_FONT;
606 if (brace == 0 && (flags & FLAG_BRACE_LAST))
609 array.push_back('}', LM_TC_TEX);
613 array.push_back('[', LM_TC_CONST);
617 if (flags & FLAG_BRACK_END)
620 array.push_back(']', LM_TC_CONST);
625 lastScriptInset(array, true, false, limits)->cell(0), FLAG_ITEM);
630 lastScriptInset(array, false, true, limits)->cell(1), FLAG_ITEM);
634 limits = yylval.l->id;
635 //lyxerr << "setting limit to " << limits << "\n";
639 if (flags & FLAG_AMPERSAND) {
640 flags &= ~FLAG_AMPERSAND;
644 lyxerr[Debug::MATHED]
645 << "found tab unexpectedly, array: '" << array << "'\n";
649 if (flags & FLAG_NEWLINE) {
650 flags &= ~FLAG_NEWLINE;
654 lyxerr[Debug::MATHED]
655 << "found newline unexpectedly, array: '" << array << "'\n";
663 array.push_back(new MathBigopInset(yylval.l));
668 array.push_back(new MathFuncLimInset(yylval.l));
673 array.push_back(new MathSymbolInset(yylval.l));
677 array.push_back(yylval.i, LM_TC_BOP);
682 array.push_back(new MathSpaceInset(yylval.i));
686 array.push_back(new MathDotsInset(yylval.l));
690 handle_frac(array, "atop");
694 handle_frac(array, "stackrel");
698 handle_frac(array, "frac");
703 unsigned char c = getuchar(yyis);
705 array.push_back(new MathRootInset);
706 mathed_parse_into(array.back()->cell(0), FLAG_BRACK_END);
707 mathed_parse_into(array.back()->cell(1), FLAG_ITEM);
710 array.push_back(new MathSqrtInset);
711 mathed_parse_into(array.back()->cell(0), FLAG_ITEM);
721 else if (ld == LM_TK_STR || ld == LM_TK_BOP || ld == LM_TK_SPECIAL)
725 mathed_parse_into(ar, FLAG_RIGHT);
730 else if (rd == LM_TK_STR || rd == LM_TK_BOP || rd == LM_TK_SPECIAL)
733 MathDelimInset * dl = new MathDelimInset(ld, rd);
740 if (flags & FLAG_RIGHT) {
744 mathPrintError("Unmatched right delimiter");
749 yyvarcode = static_cast<MathTextCodes>(yylval.l->id);
750 flags |= (FLAG_BRACE | FLAG_BRACE_FONT);
755 lyxerr[Debug::MATHED] << "LM_TK_STY not implemented\n";
756 //MathArray tmp = array;
757 //MathSizeInset * p = new MathSizeInset(MathStyles(yylval.l->id));
758 //array.push_back(p);
759 //mathed_parse_into(p->cell(0), FLAG_BRACE_FONT);
764 case LM_TK_DECORATION:
766 MathDecorationInset * p = new MathDecorationInset(yylval.l);
767 mathed_parse_into(p->cell(0), FLAG_ITEM);
777 array.push_back(new MathSymbolInset(yylval.l));
781 if (MathMacroTable::hasTemplate(yytext)) {
782 MathMacro * m = MathMacroTable::cloneTemplate(yytext);
783 for (int i = 0; i < m->nargs(); ++i)
784 mathed_parse_into(m->cell(i), FLAG_ITEM);
786 m->metrics(LM_ST_TEXT);
788 array.push_back(new MathFuncInset(yytext));
799 MathInsetTypes typ = latex_mathenv[i].typ;
801 if (typ == LM_OT_MATRIX) {
802 string const valign = lexArg('[') + 'c';
803 string const halign = lexArg('{');
804 //lyxerr << "valign: '" << valign << "'\n";
805 //lyxerr << "halign: '" << halign << "'\n";
806 MathArrayInset * m = new MathArrayInset(halign.size(), 1);
807 m->valign(valign[0]);
810 mathed_parse_lines(m, halign.size(), latex_mathenv[i].numbered, false);
812 //lyxerr << "read matrix " << *m << "\n";
815 lyxerr[Debug::MATHED] << "unknow math inset " << typ << "\n";
820 array.push_back(MathMacroTable::cloneTemplate(yylval.l->name));
824 curr_label = lexArg('{', true);
828 mathPrintError("Unrecognized token");
829 lyxerr[Debug::MATHED] << "[" << t << " " << yytext << "]" << endl;
832 } // end of big switch
834 if (flags & FLAG_LEAVE) {
835 flags &= ~FLAG_LEAVE;
840 lyxerr << " Math Panic, expect problems!" << endl;
841 // Search for the end command.
844 } while (yyis->good() && t != LM_TK_END && t);
855 MathArray mathed_parse_cell(string const & str)
857 istringstream is(str.c_str());
861 mathed_parse_into(ar, 0);
866 MathMacroTemplate * mathed_parse_macro(string const & str)
868 istringstream is(str.c_str());
869 return mathed_parse_macro(is);
873 MathMatrixInset * mathed_parse_normal(string const & str)
875 istringstream is(str.c_str());
876 return mathed_parse_normal(is);
881 MathMatrixInset * mathed_parse_normal(istream & is)
885 return mathed_parse_normal();
889 MathMacroTemplate * mathed_parse_macro(istream & is)
893 return mathed_parse_macro();
898 MathMatrixInset * mathed_parse_normal(LyXLex & lex)
900 yyis = &lex.getStream();
901 yylineno = lex.getLineNo();
903 MathMatrixInset * p = mathed_parse_normal();
905 // Update line number
906 lex.setLineNo(yylineno);
908 // reading of end_inset
911 if (lex.getString() == "\\end_inset")
913 lyxerr[Debug::MATHED] << "InsetFormula::Read: Garbage before \\end_inset,"
914 " or missing \\end_inset!" << endl;
920 MathMacroTemplate * mathed_parse_macro(LyXLex & lex)
922 yyis = &lex.getStream();
923 yylineno = lex.getLineNo();
925 MathMacroTemplate * p = mathed_parse_macro();
927 // Update line number
928 lex.setLineNo(yylineno);
930 // reading of end_inset
933 if (lex.getString() == "\\end_inset")
935 lyxerr[Debug::MATHED] << "InsetFormula::Read: Garbage before \\end_inset,"
936 " or missing \\end_inset!" << endl;