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_rootinset.h"
45 #include "math_scriptinset.h"
46 #include "math_sizeinset.h"
47 #include "math_spaceinset.h"
48 #include "math_sqrtinset.h"
49 #include "math_stackrelinset.h"
50 #include "math_symbolinset.h"
52 #include "mathed/support.h"
54 #include "support/lstrings.h"
61 // These are lexical codes, not semantic
67 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[':']
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 latexkeys const * l = in_word_set(s);
290 //lyxerr << "found special token for '" << l->name
291 // << "' : " << l->id << " \n";
295 if (lexcode[c] == LexAlpha) {
297 while (lexcode[c] == LexAlpha && yyis->good()) {
301 while (lexcode[c] == LexSpace && yyis->good())
303 if (lexcode[c] != LexSpace)
306 //lyxerr[Debug::MATHED] << "reading: text '" << yytext << "'\n";
307 latexkeys const * l = in_word_set(yytext);
311 if (l->token == LM_TK_BEGIN || l->token == LM_TK_END) {
312 string name = lexArg('{');
314 while (i < latex_mathenv_num && name != latex_mathenv[i].name)
317 } else if (l->token == LM_TK_SPACE)
329 MathScriptInset * prevScriptInset(MathArray const & array)
331 MathInset * p = array.back();
332 return (p && p->isScriptInset()) ? static_cast<MathScriptInset *>(p) : 0;
336 MathInset * lastScriptInset(MathArray & array, bool up, bool down, int limits)
338 MathScriptInset * p = prevScriptInset(array);
340 MathInset * b = array.back();
341 if (b && b->isScriptable()) {
342 p = new MathScriptInset(up, down, b->clone());
345 p = new MathScriptInset(up, down);
359 static bool curr_num;
360 static string curr_label;
362 void mathed_parse_lines(MathGridInset * p, int col, bool numbered, bool outmost)
364 // save global variables
365 bool const saved_num = curr_num;
366 string const saved_label = curr_label;
368 for (int row = 0; true; ++row) {
369 // reset global variables
374 int idx = p->nargs() - p->ncols();
375 for (int i = 0; i < col - 1; ++i, ++idx)
376 mathed_parse_into(p->cell(idx), FLAG_AMPERSAND);
377 mathed_parse_into(p->cell(idx), FLAG_NEWLINE | FLAG_END);
380 MathMatrixInset * m = static_cast<MathMatrixInset *>(p);
381 m->numbered(row, curr_num);
382 m->label(row, curr_label);
395 // restore global variables
396 curr_num = saved_num;
397 curr_label = saved_label;
401 MathMacroTemplate * mathed_parse_macro()
403 if (yylex() != LM_TK_NEWCOMMAND) {
404 lyxerr << "\\newcommand expected\n";
408 string name = lexArg('{').substr(1);
409 string arg = lexArg('[');
410 int narg = arg.empty() ? 0 : atoi(arg.c_str());
411 MathMacroTemplate * p = new MathMacroTemplate(name, narg);
412 mathed_parse_into(p->cell(0), FLAG_BRACE | FLAG_BRACE_LAST);
417 MathMatrixInset * mathed_parse_normal()
419 MathMatrixInset * p = 0;
426 lyxerr[Debug::MATHED]
427 << "reading math environment " << i << " "
428 << latex_mathenv[i].name << "\n";
430 MathInsetTypes typ = latex_mathenv[i].typ;
431 p = new MathMatrixInset(typ);
436 curr_num = latex_mathenv[i].numbered;
438 mathed_parse_into(p->cell(0), 0);
439 p->numbered(0, curr_num);
440 p->label(0, curr_label);
444 case LM_OT_EQUATION: {
445 curr_num = latex_mathenv[i].numbered;
447 mathed_parse_into(p->cell(0), FLAG_END);
448 p->numbered(0, curr_num);
449 p->label(0, curr_label);
453 case LM_OT_EQNARRAY: {
454 mathed_parse_lines(p, 3, latex_mathenv[i].numbered, true);
459 p->halign(lexArg('{'));
460 mathed_parse_lines(p, 2, latex_mathenv[i].numbered, true);
464 case LM_OT_ALIGNAT: {
465 p->halign(lexArg('{'));
466 mathed_parse_lines(p, 2, latex_mathenv[i].numbered, true);
471 lyxerr[Debug::MATHED]
472 << "1: unknown math environment: " << typ << "\n";
479 lyxerr[Debug::MATHED]
480 << "2 unknown math environment: " << t << "\n";
487 void mathed_parse_into(MathArray & array, unsigned flags)
489 static int plevel = -1;
492 MathTextCodes yyvarcode = LM_TC_VAR;
500 //lyxerr << "t: " << t << " flags: " << flags << " i: " << yylval.i
501 // << " '" << yytext << "'\n";
502 //array.dump(lyxerr);
505 if (flags & FLAG_ITEM) {
507 if (t == LM_TK_OPEN) {
508 // skip the brace and regard everything to the next matching
512 flags |= FLAG_BRACE_LAST;
514 // regard only this single token
519 if ((flags & FLAG_BRACE) && t != LM_TK_OPEN) {
521 "Expected {. Maybe you forgot to enclose an argument in {}");
529 if (!isspace(yylval.i) || yyvarcode == LM_TC_TEXTRM)
530 array.push_back(new MathCharInset(yylval.i, yyvarcode));
533 case LM_TK_ARGUMENT: {
534 MathMacroArgument * p = new MathMacroArgument(yylval.i);
541 array.push_back(new MathCharInset(yylval.i, LM_TC_SPECIAL));
545 array.push_back(new MathCharInset(yylval.i, LM_TC_CONST));
550 if (flags & FLAG_BRACE)
551 flags &= ~FLAG_BRACE;
553 array.push_back(new MathCharInset('{', LM_TC_TEX));
559 mathPrintError("Unmatching braces");
563 if (flags & FLAG_BRACE_FONT) {
564 yyvarcode = LM_TC_VAR;
565 flags &= ~FLAG_BRACE_FONT;
568 if (brace == 0 && (flags & FLAG_BRACE_LAST))
571 array.push_back(new MathCharInset('}', LM_TC_TEX));
575 array.push_back(new MathCharInset('[', LM_TC_CONST));
579 if (flags & FLAG_BRACK_END)
582 array.push_back(new MathCharInset(']', LM_TC_CONST));
587 lastScriptInset(array, true, false, limits)->cell(0), FLAG_ITEM);
592 lastScriptInset(array, false, true, limits)->cell(1), FLAG_ITEM);
596 limits = yylval.l->id;
597 //lyxerr << "setting limit to " << limits << "\n";
601 if (flags & FLAG_AMPERSAND) {
602 flags &= ~FLAG_AMPERSAND;
606 lyxerr[Debug::MATHED]
607 << "found tab unexpectedly, array: '" << array << "'\n";
611 if (flags & FLAG_NEWLINE) {
612 flags &= ~FLAG_NEWLINE;
616 lyxerr[Debug::MATHED]
617 << "found newline unexpectedly, array: '" << array << "'\n";
625 array.push_back(new MathBigopInset(yylval.l));
630 array.push_back(new MathFuncLimInset(yylval.l));
635 array.push_back(new MathSymbolInset(yylval.l));
639 array.push_back(new MathCharInset(yylval.i, LM_TC_BOP));
644 array.push_back(new MathSpaceInset(yylval.i));
648 array.push_back(new MathDotsInset(yylval.l));
653 MathStackrelInset * p = new MathStackrelInset;
654 mathed_parse_into(p->cell(0), FLAG_ITEM);
655 mathed_parse_into(p->cell(1), FLAG_ITEM);
662 MathFracInset * p = new MathFracInset;
663 mathed_parse_into(p->cell(0), FLAG_ITEM);
664 mathed_parse_into(p->cell(1), FLAG_ITEM);
671 unsigned char c = getuchar(yyis);
673 array.push_back(new MathRootInset);
674 mathed_parse_into(array.back()->cell(0), FLAG_BRACK_END);
675 mathed_parse_into(array.back()->cell(1), FLAG_ITEM);
678 array.push_back(new MathSqrtInset);
679 mathed_parse_into(array.back()->cell(0), FLAG_ITEM);
689 else if (ld == LM_TK_STR || ld == LM_TK_BOP || ld == LM_TK_SPECIAL)
693 mathed_parse_into(ar, FLAG_RIGHT);
698 else if (rd == LM_TK_STR || rd == LM_TK_BOP || rd == LM_TK_SPECIAL)
701 MathDelimInset * dl = new MathDelimInset(ld, rd);
708 if (flags & FLAG_RIGHT) {
712 mathPrintError("Unmatched right delimiter");
717 yyvarcode = static_cast<MathTextCodes>(yylval.l->id);
718 flags |= (FLAG_BRACE | FLAG_BRACE_FONT);
723 lyxerr[Debug::MATHED] << "LM_TK_STY not implemented\n";
724 //MathArray tmp = array;
725 //MathSizeInset * p = new MathSizeInset(MathStyles(yylval.l->id));
726 //array.push_back(p);
727 //mathed_parse_into(p->cell(0), FLAG_BRACE_FONT);
732 case LM_TK_DECORATION:
734 MathDecorationInset * p = new MathDecorationInset(yylval.l);
735 mathed_parse_into(p->cell(0), FLAG_ITEM);
745 array.push_back(new MathSymbolInset(yylval.l));
749 if (MathMacroTable::hasTemplate(yytext)) {
750 MathMacro * m = MathMacroTable::cloneTemplate(yytext);
751 for (int i = 0; i < m->nargs(); ++i)
752 mathed_parse_into(m->cell(i), FLAG_ITEM);
754 m->metrics(LM_ST_TEXT);
756 array.push_back(new MathFuncInset(yytext));
767 MathInsetTypes typ = latex_mathenv[i].typ;
769 if (typ == LM_OT_MATRIX) {
770 string const valign = lexArg('[') + 'c';
771 string const halign = lexArg('{');
772 //lyxerr << "valign: '" << valign << "'\n";
773 //lyxerr << "halign: '" << halign << "'\n";
774 MathArrayInset * m = new MathArrayInset(halign.size(), 1);
775 m->valign(valign[0]);
778 mathed_parse_lines(m, halign.size(), latex_mathenv[i].numbered, false);
780 //lyxerr << "read matrix " << *m << "\n";
783 lyxerr[Debug::MATHED] << "unknow math inset " << typ << "\n";
788 array.push_back(MathMacroTable::cloneTemplate(yylval.l->name));
792 curr_label = lexArg('{', true);
796 mathPrintError("Unrecognized token");
797 lyxerr[Debug::MATHED] << "[" << t << " " << yytext << "]" << endl;
800 } // end of big switch
802 if (flags & FLAG_LEAVE) {
803 flags &= ~FLAG_LEAVE;
808 lyxerr << " Math Panic, expect problems!" << endl;
809 // Search for the end command.
812 } while (yyis->good() && t != LM_TK_END && t);
823 MathArray mathed_parse_cell(string const & str)
825 istringstream is(str.c_str());
829 mathed_parse_into(ar, 0);
834 MathMacroTemplate * mathed_parse_macro(string const & str)
836 istringstream is(str.c_str());
837 return mathed_parse_macro(is);
841 MathMatrixInset * mathed_parse_normal(string const & str)
843 istringstream is(str.c_str());
844 return mathed_parse_normal(is);
849 MathMatrixInset * mathed_parse_normal(istream & is)
853 return mathed_parse_normal();
857 MathMacroTemplate * mathed_parse_macro(istream & is)
861 return mathed_parse_macro();
866 MathMatrixInset * mathed_parse_normal(LyXLex & lex)
868 yyis = &lex.getStream();
869 yylineno = lex.getLineNo();
871 MathMatrixInset * p = mathed_parse_normal();
873 // Update line number
874 lex.setLineNo(yylineno);
876 // reading of end_inset
879 if (lex.getString() == "\\end_inset")
881 lyxerr[Debug::MATHED] << "InsetFormula::Read: Garbage before \\end_inset,"
882 " or missing \\end_inset!" << endl;
888 MathMacroTemplate * mathed_parse_macro(LyXLex & lex)
890 yyis = &lex.getStream();
891 yylineno = lex.getLineNo();
893 MathMacroTemplate * p = mathed_parse_macro();
895 // Update line number
896 lex.setLineNo(yylineno);
898 // reading of end_inset
901 if (lex.getString() == "\\end_inset")
903 lyxerr[Debug::MATHED] << "InsetFormula::Read: Garbage before \\end_inset,"
904 " or missing \\end_inset!" << endl;