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 []
127 MathTextCodes yyvarcode;
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 (yyvarcode == LM_TC_TEXTRM && c == ' ') {
257 } else if (lexcode[c] == LexNewLine) {
260 } else if (lexcode[c] == LexComment) {
263 } while (c != '\n' && yyis->good()); // eat comments
264 } else if (lexcode[c] == LexDigit
265 || lexcode[c] == LexOther
266 || lexcode[c] == LexMathSpace) {
269 } else if (lexcode[c] == LexAlpha) {
272 } else if (lexcode[c] == LexBOP) {
275 } else if (lexcode[c] == LexMath) {
278 } else if (lexcode[c] == LexSelf) {
280 } else if (lexcode[c] == LexArgument) {
283 return LM_TK_ARGUMENT;
284 } else if (lexcode[c] == LexOpen) {
286 } else if (lexcode[c] == LexClose) {
288 } else if (lexcode[c] == LexESC) {
292 return LM_TK_NEWLINE;
295 yylval.i = LM_OT_SIMPLE;
299 yylval.i = LM_OT_SIMPLE;
303 yylval.i = LM_OT_EQUATION;
307 yylval.i = LM_OT_EQUATION;
314 if (contains(latex_special_chars, c)) {
316 return LM_TK_SPECIAL;
318 if (lexcode[c] == LexMathSpace) {
320 for (i = 0; i < 4 && static_cast<int>(c) != latex_mathspace[i][0]; ++i)
322 yylval.i = (i < 4) ? i : 0;
325 if (lexcode[c] == LexAlpha) {
327 while (lexcode[c] == LexAlpha && yyis->good()) {
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_inset();
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_inset();
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 MathInset * mathed_parse()
434 case LM_TK_NEWCOMMAND: {
435 string const name = lexArg('{').substr(1);
436 string const arg = lexArg('[');
437 int narg = arg.empty() ? 0 : atoi(arg.c_str());
438 p = new MathMacroTemplate(name, narg);
439 mathed_parse_into(p->cell(0), FLAG_BRACE | FLAG_BRACE_LAST);
440 //lyxerr[Debug::MATHED] << "LM_TK_NEWCOMMAND: name: "
441 // << name << " nargs: " << narg << "\n";
448 lyxerr[Debug::MATHED]
449 << "reading math environment " << i << " "
450 << latex_mathenv[i].name << "\n";
452 MathInsetTypes typ = latex_mathenv[i].typ;
453 p = new MathMatrixInset(typ);
454 MathMatrixInset * m = static_cast<MathMatrixInset *>(p);
458 curr_num = latex_mathenv[i].numbered;
460 mathed_parse_into(m->cell(0), 0);
461 m->numbered(0, curr_num);
462 m->label(0, curr_label);
466 case LM_OT_EQUATION: {
467 curr_num = latex_mathenv[i].numbered;
469 mathed_parse_into(m->cell(0), FLAG_END);
470 m->numbered(0, curr_num);
471 m->label(0, curr_label);
475 case LM_OT_EQNARRAY: {
476 mathed_parse_lines(m, 3, latex_mathenv[i].numbered, true);
481 m->halign(lexArg('{'));
482 mathed_parse_lines(m, 2, latex_mathenv[i].numbered, true);
486 case LM_OT_ALIGNAT: {
487 m->halign(lexArg('{'));
488 mathed_parse_lines(m, 2, latex_mathenv[i].numbered, true);
493 lyxerr[Debug::MATHED]
494 << "1: unknown math environment: " << typ << "\n";
497 p->setName(latex_mathenv[i].basename);
503 lyxerr[Debug::MATHED]
504 << "2 unknown math environment: " << t << "\n";
511 void handle_frac(MathArray & array, string const & name)
513 MathFracInset * p = new MathFracInset(name);
514 mathed_parse_into(p->cell(0), FLAG_ITEM);
515 mathed_parse_into(p->cell(1), FLAG_ITEM);
520 void mathed_parse_into(MathArray & array, unsigned flags)
522 static int plevel = -1;
525 yyvarcode = LM_TC_VAR;
533 //lyxerr << "t: " << t << " flags: " << flags << " i: " << yylval.i
534 // << " '" << yytext << "'\n";
535 //array.dump(lyxerr);
538 if (flags & FLAG_ITEM) {
540 if (t == LM_TK_OPEN) {
541 // skip the brace and regard everything to the next matching
545 flags |= FLAG_BRACE_LAST;
547 // regard only this single token
552 if ((flags & FLAG_BRACE) && t != LM_TK_OPEN) {
554 "Expected {. Maybe you forgot to enclose an argument in {}");
562 array.push_back(yylval.i, yyvarcode);
566 array.push_back(new MathMacroArgument(yylval.i));
570 array.push_back(yylval.i, LM_TC_SPECIAL);
574 array.push_back(yylval.i, LM_TC_CONST);
579 if (flags & FLAG_BRACE)
580 flags &= ~FLAG_BRACE;
582 array.push_back('{', LM_TC_TEX);
588 mathPrintError("Unmatching braces");
592 if (flags & FLAG_BRACE_FONT) {
593 yyvarcode = LM_TC_VAR;
594 flags &= ~FLAG_BRACE_FONT;
597 if (brace == 0 && (flags & FLAG_BRACE_LAST))
600 array.push_back('}', LM_TC_TEX);
604 array.push_back('[', LM_TC_CONST);
608 if (flags & FLAG_BRACK_END)
611 array.push_back(']', LM_TC_CONST);
616 lastScriptInset(array, true, false, limits)->cell(0), FLAG_ITEM);
621 lastScriptInset(array, false, true, limits)->cell(1), FLAG_ITEM);
625 limits = yylval.l->id;
626 //lyxerr << "setting limit to " << limits << "\n";
630 if (flags & FLAG_AMPERSAND) {
631 flags &= ~FLAG_AMPERSAND;
635 lyxerr[Debug::MATHED]
636 << "found tab unexpectedly, array: '" << array << "'\n";
640 if (flags & FLAG_NEWLINE) {
641 flags &= ~FLAG_NEWLINE;
645 lyxerr[Debug::MATHED]
646 << "found newline unexpectedly, array: '" << array << "'\n";
656 array.push_back(new MathSymbolInset(yylval.l));
660 array.push_back(yylval.i, LM_TC_BOP);
665 array.push_back(new MathSpaceInset(yylval.i));
669 array.push_back(new MathDotsInset(yylval.l));
673 handle_frac(array, "atop");
677 handle_frac(array, "stackrel");
681 handle_frac(array, "frac");
686 unsigned char c = getuchar(yyis);
688 array.push_back(new MathRootInset);
689 mathed_parse_into(array.back_inset()->cell(0), FLAG_BRACK_END);
690 mathed_parse_into(array.back_inset()->cell(1), FLAG_ITEM);
693 array.push_back(new MathSqrtInset);
694 mathed_parse_into(array.back_inset()->cell(0), FLAG_ITEM);
704 else if (ld == LM_TK_STR || ld == LM_TK_BOP || ld == LM_TK_SPECIAL)
708 mathed_parse_into(ar, FLAG_RIGHT);
713 else if (rd == LM_TK_STR || rd == LM_TK_BOP || rd == LM_TK_SPECIAL)
716 MathDelimInset * dl = new MathDelimInset(ld, rd);
723 if (flags & FLAG_RIGHT) {
727 mathPrintError("Unmatched right delimiter");
732 yyvarcode = static_cast<MathTextCodes>(yylval.l->id);
733 flags |= (FLAG_BRACE | FLAG_BRACE_FONT);
738 lyxerr[Debug::MATHED] << "LM_TK_STY not implemented\n";
739 //MathArray tmp = array;
740 //MathSizeInset * p = new MathSizeInset(MathStyles(yylval.l->id));
741 //array.push_back(p);
742 //mathed_parse_into(p->cell(0), FLAG_BRACE_FONT);
747 case LM_TK_DECORATION:
749 MathDecorationInset * p = new MathDecorationInset(yylval.l);
750 mathed_parse_into(p->cell(0), FLAG_ITEM);
760 array.push_back(new MathSymbolInset(yylval.l));
764 if (MathMacroTable::hasTemplate(yytext)) {
765 MathMacro * m = MathMacroTable::cloneTemplate(yytext);
766 for (int i = 0; i < m->nargs(); ++i)
767 mathed_parse_into(m->cell(i), FLAG_ITEM);
769 m->metrics(LM_ST_TEXT);
771 array.push_back(new MathFuncInset(yytext));
782 MathInsetTypes typ = latex_mathenv[i].typ;
784 if (typ == LM_OT_MATRIX) {
785 string const valign = lexArg('[') + 'c';
786 string const halign = lexArg('{');
787 //lyxerr << "valign: '" << valign << "'\n";
788 //lyxerr << "halign: '" << halign << "'\n";
789 MathArrayInset * m = new MathArrayInset(halign.size(), 1);
790 m->valign(valign[0]);
793 mathed_parse_lines(m, halign.size(), latex_mathenv[i].numbered, false);
795 //lyxerr << "read matrix " << *m << "\n";
798 lyxerr[Debug::MATHED] << "unknow math inset " << typ << "\n";
803 array.push_back(MathMacroTable::cloneTemplate(yylval.l->name));
807 curr_label = lexArg('{', true);
811 mathPrintError("Unrecognized token");
812 lyxerr[Debug::MATHED] << "[" << t << " " << yytext << "]" << endl;
815 } // end of big switch
817 if (flags & FLAG_LEAVE) {
818 flags &= ~FLAG_LEAVE;
823 lyxerr << " Math Panic, expect problems!" << endl;
824 // Search for the end command.
827 } while (yyis->good() && t != LM_TK_END && t);
838 MathArray mathed_parse_cell(string const & str)
840 istringstream is(str.c_str());
844 mathed_parse_into(ar, 0);
849 MathInset * mathed_parse(string const & str)
851 istringstream is(str.c_str());
852 return mathed_parse(is);
856 MathInset * mathed_parse(istream & is)
860 return mathed_parse();
864 MathInset * mathed_parse(LyXLex & lex)
866 yyis = &lex.getStream();
867 yylineno = lex.GetLineNo();
869 MathInset * p = mathed_parse();
871 // Update line number
872 lex.setLineNo(yylineno);
874 // reading of end_inset
877 if (lex.GetString() == "\\end_inset")
879 lyxerr[Debug::MATHED] << "InsetFormula::Read: Garbage before \\end_inset,"
880 " or missing \\end_inset!" << endl;