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(MathArray & array, unsigned flags);
86 unsigned char getuchar(std::istream * is)
90 return static_cast<unsigned char>(c);
93 const unsigned char LM_TK_OPEN = '{';
94 const unsigned char LM_TK_CLOSE = '}';
97 FLAG_BRACE = 1 << 0, // A { needed //}
98 FLAG_BRACE_LAST = 1 << 1, // // { Last } ends the parsing process
99 FLAG_RIGHT = 1 << 2, // Next right ends the parsing process
100 FLAG_END = 1 << 3, // Next end ends the parsing process
101 FLAG_BRACE_FONT = 1 << 4, // // { Next } closes a font
102 FLAG_BRACK_END = 1 << 5, // // [ Next ] ends the parsing process
103 FLAG_AMPERSAND = 1 << 6, // Next & ends the parsing process
104 FLAG_NEWLINE = 1 << 7, // Next \\ ends the parsing process
105 FLAG_ITEM = 1 << 8, // read a (possibly braced token)
106 FLAG_LEAVE = 1 << 9, // marker for leaving the
107 FLAG_OPTARG = 1 << 10 // reads an argument in []
123 MathTextCodes yyvarcode;
127 struct latex_mathenv_type {
129 char const * basename;
135 latex_mathenv_type latex_mathenv[] = {
136 {"math", "math", LM_OT_SIMPLE, 0, 0},
137 {"equation*", "equation", LM_OT_EQUATION, 0, 0},
138 {"equation", "equation", LM_OT_EQUATION, 1, 0},
139 {"eqnarray*", "eqnarray", LM_OT_EQNARRAY, 0, 0},
140 {"eqnarray", "eqnarray", LM_OT_EQNARRAY, 1, 0},
141 {"align*", "align", LM_OT_ALIGN, 0, 1},
142 {"align", "align", LM_OT_ALIGN, 1, 1},
143 {"alignat*", "alignat", LM_OT_ALIGNAT, 0, 1},
144 {"alignat", "alignat", LM_OT_ALIGNAT, 1, 1},
145 {"multline*", "multline", LM_OT_MULTLINE, 0, 1},
146 {"multline", "multline", LM_OT_MULTLINE, 1, 1},
147 {"array", "array", LM_OT_MATRIX, 0, 1}
150 int const latex_mathenv_num = sizeof(latex_mathenv)/sizeof(latex_mathenv[0]);
154 void mathPrintError(string const & msg)
156 //lyxerr[Debug::MATHED] << "Line ~" << yylineno << ": Math parse error: " << msg << endl;
157 lyxerr << "Line ~" << yylineno << ": Math parse error: " << msg << endl;
163 for (int i = 0; i <= 255; ++i) {
165 lexcode[i] = LexDigit;
167 lexcode[i] = LexSpace;
169 lexcode[i] = LexAlpha;
172 lexcode['\t'] = lexcode['\f'] = lexcode[' '] = LexSpace;
173 lexcode['\n'] = LexNewLine;
174 lexcode['%'] = LexComment;
175 lexcode['#'] = LexArgument;
176 lexcode['$'] = LexMath;
177 lexcode['+'] = lexcode['-'] = lexcode['*'] = lexcode['/']
178 = lexcode['<'] = lexcode['>'] = lexcode['='] = LexBOP;
180 lexcode['!'] = lexcode[','] = lexcode[':']
181 = lexcode[';'] = LexMathSpace;
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 (yyvarcode == LM_TC_TEXTRM && c == ' ') {
253 } else 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) {
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()) {
329 //lyxerr[Debug::MATHED] << "reading: text '" << yytext << "'\n";
330 latexkeys const * l = in_word_set(yytext);
334 if (l->token == LM_TK_BEGIN || l->token == LM_TK_END) {
335 string name = lexArg('{');
337 while (i < latex_mathenv_num && name != latex_mathenv[i].name)
340 } else if (l->token == LM_TK_SPACE)
353 MathScriptInset * prevScriptInset(MathArray const & array)
355 MathInset * p = array.back_inset();
356 return (p && p->isScriptInset()) ? static_cast<MathScriptInset *>(p) : 0;
360 MathInset * lastScriptInset(MathArray & array, bool up, bool down, int limits)
362 MathScriptInset * p = prevScriptInset(array);
364 MathInset * b = array.back_inset();
365 if (b && b->isScriptable()) {
366 p = new MathScriptInset(up, down, b->clone());
369 p = new MathScriptInset(up, down);
384 static bool curr_num;
385 static string curr_label;
387 void mathed_parse_lines(MathInset * inset, int col, bool numbered, bool outmost)
389 // save global variables
390 bool saved_num = curr_num;
391 string saved_label = curr_label;
393 MathGridInset * p = static_cast<MathGridInset *>(inset);
394 for (int row = 0; true; ++row) {
395 // reset global variables
397 curr_label = string();
400 int idx = p->nargs() - p->ncols();
401 for (int i = 0; i < col - 1; ++i, ++idx)
402 mathed_parse(p->cell(idx), FLAG_AMPERSAND);
403 mathed_parse(p->cell(idx), FLAG_NEWLINE | FLAG_END);
406 MathMatrixInset * m = static_cast<MathMatrixInset *>(p);
407 m->numbered(row, curr_num);
408 m->label(row, curr_label);
419 // restore global variables
420 curr_num = saved_num;
421 curr_label = saved_label;
425 MathInset * mathed_parse()
431 case LM_TK_NEWCOMMAND: {
432 string name = lexArg('{').substr(1);
433 string arg = lexArg('[');
434 int narg = arg.empty() ? 0 : atoi(arg.c_str());
435 p = new MathMacroTemplate(name, narg);
436 mathed_parse(p->cell(0), FLAG_BRACE | FLAG_BRACE_LAST);
437 //lyxerr[Debug::MATHED] << "LM_TK_NEWCOMMAND: name: "
438 // << name << " nargs: " << narg << "\n";
445 lyxerr[Debug::MATHED]
446 << "reading math environment " << i << " "
447 << latex_mathenv[i].name << "\n";
449 MathInsetTypes typ = latex_mathenv[i].typ;
450 p = new MathMatrixInset(typ);
451 MathMatrixInset * m = static_cast<MathMatrixInset *>(p);
455 curr_num = latex_mathenv[i].numbered;
456 curr_label = string();
457 mathed_parse(m->cell(0), 0);
458 m->numbered(0, curr_num);
459 m->label(0, curr_label);
463 case LM_OT_EQUATION: {
464 curr_num = latex_mathenv[i].numbered;
465 curr_label = string();
466 mathed_parse(m->cell(0), FLAG_END);
467 m->numbered(0, curr_num);
468 m->label(0, curr_label);
472 case LM_OT_EQNARRAY: {
473 mathed_parse_lines(m, 3, latex_mathenv[i].numbered, true);
478 m->halign(lexArg('{'));
479 mathed_parse_lines(m, 2, latex_mathenv[i].numbered, true);
483 case LM_OT_ALIGNAT: {
484 m->halign(lexArg('{'));
485 mathed_parse_lines(m, 2, latex_mathenv[i].numbered, true);
490 lyxerr[Debug::MATHED]
491 << "1: unknown math environment: " << typ << "\n";
494 p->setName(latex_mathenv[i].basename);
500 lyxerr[Debug::MATHED]
501 << "2 unknown math environment: " << t << "\n";
508 void handle_frac(MathArray & array, string const & name)
510 MathFracInset * p = new MathFracInset(name);
511 mathed_parse(p->cell(0), FLAG_ITEM);
512 mathed_parse(p->cell(1), FLAG_ITEM);
517 void mathed_parse(MathArray & array, unsigned flags)
519 static int plevel = -1;
522 yyvarcode = LM_TC_VAR;
530 //lyxerr << "t: " << t << " flags: " << flags << " i: " << yylval.i
531 // << " '" << yytext << "'\n";
532 //array.dump(lyxerr);
535 if (flags & FLAG_ITEM) {
537 if (t == LM_TK_OPEN) {
538 // skip the brace and regard everything to the next matching
542 flags |= FLAG_BRACE_LAST;
544 // regard only this single token
549 if ((flags & FLAG_BRACE) && t != LM_TK_OPEN) {
551 "Expected {. Maybe you forgot to enclose an argument in {}");
559 array.push_back(yylval.i, yyvarcode);
563 array.push_back(new MathMacroArgument(yylval.i));
567 array.push_back(yylval.i, LM_TC_SPECIAL);
571 array.push_back(yylval.i, LM_TC_CONST);
576 if (flags & FLAG_BRACE)
577 flags &= ~FLAG_BRACE;
579 array.push_back('{', LM_TC_TEX);
585 mathPrintError("Unmatching braces");
589 if (flags & FLAG_BRACE_FONT) {
590 yyvarcode = LM_TC_VAR;
591 flags &= ~FLAG_BRACE_FONT;
594 if (brace == 0 && (flags & FLAG_BRACE_LAST))
597 array.push_back('}', LM_TC_TEX);
601 array.push_back('[', LM_TC_CONST);
605 if (flags & FLAG_BRACK_END)
608 array.push_back(']', LM_TC_CONST);
613 lastScriptInset(array, true, false, limits)->cell(0), FLAG_ITEM);
618 lastScriptInset(array, false, true, limits)->cell(1), FLAG_ITEM);
622 limits = yylval.l->id;
623 //lyxerr << "setting limit to " << limits << "\n";
627 if (flags & FLAG_AMPERSAND) {
628 flags &= ~FLAG_AMPERSAND;
632 lyxerr[Debug::MATHED]
633 << "found tab unexpectedly, array: '" << array << "'\n";
637 if (flags & FLAG_NEWLINE) {
638 flags &= ~FLAG_NEWLINE;
642 lyxerr[Debug::MATHED]
643 << "found newline unexpectedly, array: '" << array << "'\n";
653 array.push_back(new MathSymbolInset(yylval.l));
657 array.push_back(yylval.i, LM_TC_BOP);
662 array.push_back(new MathSpaceInset(yylval.i));
666 array.push_back(new MathDotsInset(yylval.l));
670 handle_frac(array, "atop");
674 handle_frac(array, "stackrel");
678 handle_frac(array, "frac");
683 unsigned char c = getuchar(yyis);
685 array.push_back(new MathRootInset);
686 mathed_parse(array.back_inset()->cell(0), FLAG_BRACK_END);
687 mathed_parse(array.back_inset()->cell(1), FLAG_ITEM);
690 array.push_back(new MathSqrtInset);
691 mathed_parse(array.back_inset()->cell(0), FLAG_ITEM);
701 else if (ld == LM_TK_STR || ld == LM_TK_BOP || ld == LM_TK_SPECIAL)
705 mathed_parse(ar, FLAG_RIGHT);
710 else if (rd == LM_TK_STR || rd == LM_TK_BOP || rd == LM_TK_SPECIAL)
713 MathDelimInset * dl = new MathDelimInset(ld, rd);
720 if (flags & FLAG_RIGHT) {
724 mathPrintError("Unmatched right delimiter");
729 yyvarcode = static_cast<MathTextCodes>(yylval.l->id);
730 flags |= (FLAG_BRACE | FLAG_BRACE_FONT);
735 lyxerr[Debug::MATHED] << "LM_TK_STY not implemented\n";
736 //MathArray tmp = array;
737 //MathSizeInset * p = new MathSizeInset(MathStyles(yylval.l->id));
738 //array.push_back(p);
739 //mathed_parse(p->cell(0), FLAG_BRACE_FONT);
744 case LM_TK_DECORATION:
746 MathDecorationInset * p = new MathDecorationInset(yylval.l);
747 mathed_parse(p->cell(0), FLAG_ITEM);
757 array.push_back(new MathSymbolInset(yylval.l));
761 if (MathMacroTable::hasTemplate(yytext)) {
762 MathMacro * m = MathMacroTable::cloneTemplate(yytext);
763 for (int i = 0; i < m->nargs(); ++i)
764 mathed_parse(m->cell(i), FLAG_ITEM);
766 m->metrics(LM_ST_TEXT);
768 array.push_back(new MathFuncInset(yytext));
779 MathInsetTypes typ = latex_mathenv[i].typ;
781 if (typ == LM_OT_MATRIX) {
782 string valign = lexArg('[') + 'c';
783 string halign = lexArg('{');
784 //lyxerr << "valign: '" << valign << "'\n";
785 //lyxerr << "halign: '" << halign << "'\n";
786 MathArrayInset * m = new MathArrayInset(halign.size(), 1);
787 m->valign(valign[0]);
790 mathed_parse_lines(m, halign.size(), latex_mathenv[i].numbered, false);
792 //lyxerr << "read matrix " << *m << "\n";
795 lyxerr[Debug::MATHED] << "unknow math inset " << typ << "\n";
800 array.push_back(MathMacroTable::cloneTemplate(yylval.l->name));
804 curr_label = lexArg('{', true);
808 mathPrintError("Unrecognized token");
809 lyxerr[Debug::MATHED] << "[" << t << " " << yytext << "]" << endl;
812 } // end of big switch
814 if (flags & FLAG_LEAVE) {
815 flags &= ~FLAG_LEAVE;
820 lyxerr << " Math Panic, expect problems!" << endl;
821 // Search for the end command.
824 } while (yyis->good() && t != LM_TK_END && t);
835 MathArray mathed_parse_cell(string const & str)
837 istringstream is(str.c_str());
846 MathInset * mathed_parse(string const & str)
848 istringstream is(str.c_str());
849 return mathed_parse(is);
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;