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_stackrelinset.h"
49 #include "math_symbolinset.h"
51 #include "mathed/support.h"
53 #include "support/lstrings.h"
60 // These are lexical codes, not semantic
66 LexBOP, // Binary operators or relations
79 lexcode_enum lexcode[256];
82 char const * latex_special_chars = "#$%&_{}";
87 void mathed_parse_into(MathArray & array, unsigned flags);
89 unsigned char getuchar(std::istream * is)
94 lyxerr << "The input stream is not well..." << endl;
96 return static_cast<unsigned char>(c);
99 const unsigned char LM_TK_OPEN = '{';
100 const unsigned char LM_TK_CLOSE = '}';
103 FLAG_BRACE = 1 << 0, // A { needed //}
104 FLAG_BRACE_LAST = 1 << 1, // // { Last } ends the parsing process
105 FLAG_RIGHT = 1 << 2, // Next right ends the parsing process
106 FLAG_END = 1 << 3, // Next end ends the parsing process
107 FLAG_BRACE_FONT = 1 << 4, // // { Next } closes a font
108 FLAG_BRACK_END = 1 << 5, // // [ Next ] ends the parsing process
109 FLAG_AMPERSAND = 1 << 6, // Next & ends the parsing process
110 FLAG_NEWLINE = 1 << 7, // Next \\ ends the parsing process
111 FLAG_ITEM = 1 << 8, // read a (possibly braced token)
112 FLAG_LEAVE = 1 << 9, // marker for leaving the
113 FLAG_OPTARG = 1 << 10 // reads an argument in []
132 struct latex_mathenv_type {
134 char const * basename;
140 latex_mathenv_type latex_mathenv[] = {
141 {"math", "math", LM_OT_SIMPLE, 0, 0},
142 {"equation*", "equation", LM_OT_EQUATION, 0, 0},
143 {"equation", "equation", LM_OT_EQUATION, 1, 0},
144 {"eqnarray*", "eqnarray", LM_OT_EQNARRAY, 0, 0},
145 {"eqnarray", "eqnarray", LM_OT_EQNARRAY, 1, 0},
146 {"align*", "align", LM_OT_ALIGN, 0, 1},
147 {"align", "align", LM_OT_ALIGN, 1, 1},
148 {"alignat*", "alignat", LM_OT_ALIGNAT, 0, 1},
149 {"alignat", "alignat", LM_OT_ALIGNAT, 1, 1},
150 {"multline*", "multline", LM_OT_MULTLINE, 0, 1},
151 {"multline", "multline", LM_OT_MULTLINE, 1, 1},
152 {"array", "array", LM_OT_MATRIX, 0, 1}
155 int const latex_mathenv_num = sizeof(latex_mathenv)/sizeof(latex_mathenv[0]);
159 void mathPrintError(string const & msg)
161 //lyxerr[Debug::MATHED] << "Line ~" << yylineno << ": Math parse error: " << msg << endl;
162 lyxerr << "Line ~" << yylineno << ": Math parse error: " << msg << endl;
168 for (int i = 0; i <= 255; ++i) {
170 lexcode[i] = LexDigit;
172 lexcode[i] = LexSpace;
174 lexcode[i] = LexAlpha;
177 lexcode['\t'] = lexcode['\f'] = lexcode[' '] = LexSpace;
178 lexcode['\n'] = LexNewLine;
179 lexcode['%'] = LexComment;
180 lexcode['#'] = LexArgument;
181 lexcode['$'] = LexMath;
182 lexcode['+'] = lexcode['-'] = lexcode['*'] = lexcode['/']
183 = lexcode['<'] = lexcode['>'] = lexcode['='] = LexBOP;
185 lexcode['!'] = lexcode[','] = lexcode[':']
186 = lexcode[';'] = LexMathSpace;
188 lexcode['('] = lexcode[')'] = lexcode['|'] = lexcode['.'] =
189 lexcode['?'] = LexOther;
191 lexcode['\''] = lexcode['@'] = LexAlpha;
193 lexcode['['] = lexcode[']'] = lexcode['^'] = lexcode['_'] =
194 lexcode['&'] = LexSelf;
196 lexcode['\\'] = LexESC;
197 lexcode['{'] = LexOpen;
198 lexcode['}'] = LexClose;
202 string lexArg(unsigned char lf, bool accept_spaces = false)
206 while (yyis->good()) {
217 unsigned char rg = 0;
218 if (lf == '{') rg = '}';
219 if (lf == '[') rg = ']';
220 if (lf == '(') rg = ')';
222 lyxerr[Debug::MATHED] << "Math parse error: unknown bracket '"
223 << lf << "'" << endl;
229 unsigned char c = getuchar(yyis);
234 if ((!isspace(c) || (c == ' ' && accept_spaces)) && depth > 0)
236 } while (depth > 0 && yyis->good());
244 static bool init_done = false;
251 while (yyis->good()) {
252 unsigned char c = getuchar(yyis);
253 //lyxerr << "reading byte: '" << c << "' code: " << lexcode[c] << endl;
255 if (lexcode[c] == LexNewLine) {
258 } else if (lexcode[c] == LexComment) {
261 } while (c != '\n' && yyis->good()); // eat comments
262 } else if (lexcode[c] == LexDigit
263 || lexcode[c] == LexOther
264 || lexcode[c] == LexMathSpace) {
267 } else if (lexcode[c] == LexAlpha || lexcode[c] == LexSpace) {
270 } else if (lexcode[c] == LexBOP) {
273 } else if (lexcode[c] == LexMath) {
276 } else if (lexcode[c] == LexSelf) {
278 } else if (lexcode[c] == LexArgument) {
281 return LM_TK_ARGUMENT;
282 } else if (lexcode[c] == LexOpen) {
284 } else if (lexcode[c] == LexClose) {
286 } else if (lexcode[c] == LexESC) {
290 return LM_TK_NEWLINE;
293 yylval.i = LM_OT_SIMPLE;
297 yylval.i = LM_OT_SIMPLE;
301 yylval.i = LM_OT_EQUATION;
305 yylval.i = LM_OT_EQUATION;
312 if (contains(latex_special_chars, c)) {
314 return LM_TK_SPECIAL;
316 if (lexcode[c] == LexMathSpace) {
318 for (i = 0; i < 4 && static_cast<int>(c) != latex_mathspace[i][0]; ++i)
320 yylval.i = (i < 4) ? i : 0;
323 if (lexcode[c] == LexAlpha) {
325 while (lexcode[c] == LexAlpha && yyis->good()) {
329 while (lexcode[c] == LexSpace && yyis->good())
331 if (lexcode[c] != LexSpace)
334 //lyxerr[Debug::MATHED] << "reading: text '" << yytext << "'\n";
335 latexkeys const * l = in_word_set(yytext);
339 if (l->token == LM_TK_BEGIN || l->token == LM_TK_END) {
340 string name = lexArg('{');
342 while (i < latex_mathenv_num && name != latex_mathenv[i].name)
345 } else if (l->token == LM_TK_SPACE)
357 MathScriptInset * prevScriptInset(MathArray const & array)
359 MathInset * p = array.back();
360 return (p && p->isScriptInset()) ? static_cast<MathScriptInset *>(p) : 0;
364 MathInset * lastScriptInset(MathArray & array, bool up, bool down, int limits)
366 MathScriptInset * p = prevScriptInset(array);
368 MathInset * b = array.back();
369 if (b && b->isScriptable()) {
370 p = new MathScriptInset(up, down, b->clone());
373 p = new MathScriptInset(up, down);
387 static bool curr_num;
388 static string curr_label;
390 void mathed_parse_lines(MathGridInset * p, int col, bool numbered, bool outmost)
392 // save global variables
393 bool const saved_num = curr_num;
394 string const saved_label = curr_label;
396 for (int row = 0; true; ++row) {
397 // reset global variables
402 int idx = p->nargs() - p->ncols();
403 for (int i = 0; i < col - 1; ++i, ++idx)
404 mathed_parse_into(p->cell(idx), FLAG_AMPERSAND);
405 mathed_parse_into(p->cell(idx), FLAG_NEWLINE | FLAG_END);
408 MathMatrixInset * m = static_cast<MathMatrixInset *>(p);
409 m->numbered(row, curr_num);
410 m->label(row, curr_label);
421 // restore global variables
422 curr_num = saved_num;
423 curr_label = saved_label;
427 MathMacroTemplate * mathed_parse_macro()
429 if (yylex() != LM_TK_NEWCOMMAND) {
430 lyxerr << "\\newcommand expected\n";
434 string name = lexArg('{').substr(1);
435 string arg = lexArg('[');
436 int narg = arg.empty() ? 0 : atoi(arg.c_str());
437 MathMacroTemplate * p = new MathMacroTemplate(name, narg);
438 mathed_parse_into(p->cell(0), FLAG_BRACE | FLAG_BRACE_LAST);
443 MathMatrixInset * mathed_parse_normal()
445 MathMatrixInset * p = 0;
452 lyxerr[Debug::MATHED]
453 << "reading math environment " << i << " "
454 << latex_mathenv[i].name << "\n";
456 MathInsetTypes typ = latex_mathenv[i].typ;
457 p = new MathMatrixInset(typ);
462 curr_num = latex_mathenv[i].numbered;
464 mathed_parse_into(p->cell(0), 0);
465 p->numbered(0, curr_num);
466 p->label(0, curr_label);
470 case LM_OT_EQUATION: {
471 curr_num = latex_mathenv[i].numbered;
473 mathed_parse_into(p->cell(0), FLAG_END);
474 p->numbered(0, curr_num);
475 p->label(0, curr_label);
479 case LM_OT_EQNARRAY: {
480 mathed_parse_lines(p, 3, latex_mathenv[i].numbered, true);
485 p->halign(lexArg('{'));
486 mathed_parse_lines(p, 2, latex_mathenv[i].numbered, true);
490 case LM_OT_ALIGNAT: {
491 p->halign(lexArg('{'));
492 mathed_parse_lines(p, 2, latex_mathenv[i].numbered, true);
497 lyxerr[Debug::MATHED]
498 << "1: unknown math environment: " << typ << "\n";
505 lyxerr[Debug::MATHED]
506 << "2 unknown math environment: " << t << "\n";
513 void mathed_parse_into(MathArray & array, unsigned flags)
515 static int plevel = -1;
518 MathTextCodes yyvarcode = LM_TC_VAR;
526 //lyxerr << "t: " << t << " flags: " << flags << " i: " << yylval.i
527 // << " '" << yytext << "'\n";
528 //array.dump(lyxerr);
531 if (flags & FLAG_ITEM) {
533 if (t == LM_TK_OPEN) {
534 // skip the brace and regard everything to the next matching
538 flags |= FLAG_BRACE_LAST;
540 // regard only this single token
545 if ((flags & FLAG_BRACE) && t != LM_TK_OPEN) {
547 "Expected {. Maybe you forgot to enclose an argument in {}");
555 if (!isspace(yylval.i) || yyvarcode == LM_TC_TEXTRM)
556 array.push_back(yylval.i, yyvarcode);
559 case LM_TK_ARGUMENT: {
560 MathMacroArgument * p = 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";
651 array.push_back(new MathBigopInset(yylval.l));
656 array.push_back(new MathFuncLimInset(yylval.l));
661 array.push_back(new MathSymbolInset(yylval.l));
665 array.push_back(yylval.i, LM_TC_BOP);
670 array.push_back(new MathSpaceInset(yylval.i));
674 array.push_back(new MathDotsInset(yylval.l));
679 MathStackrelInset * p = new MathStackrelInset;
680 mathed_parse_into(p->cell(0), FLAG_ITEM);
681 mathed_parse_into(p->cell(1), FLAG_ITEM);
688 MathFracInset * p = new MathFracInset;
689 mathed_parse_into(p->cell(0), FLAG_ITEM);
690 mathed_parse_into(p->cell(1), FLAG_ITEM);
697 unsigned char c = getuchar(yyis);
699 array.push_back(new MathRootInset);
700 mathed_parse_into(array.back()->cell(0), FLAG_BRACK_END);
701 mathed_parse_into(array.back()->cell(1), FLAG_ITEM);
704 array.push_back(new MathSqrtInset);
705 mathed_parse_into(array.back()->cell(0), FLAG_ITEM);
715 else if (ld == LM_TK_STR || ld == LM_TK_BOP || ld == LM_TK_SPECIAL)
719 mathed_parse_into(ar, FLAG_RIGHT);
724 else if (rd == LM_TK_STR || rd == LM_TK_BOP || rd == LM_TK_SPECIAL)
727 MathDelimInset * dl = new MathDelimInset(ld, rd);
734 if (flags & FLAG_RIGHT) {
738 mathPrintError("Unmatched right delimiter");
743 yyvarcode = static_cast<MathTextCodes>(yylval.l->id);
744 flags |= (FLAG_BRACE | FLAG_BRACE_FONT);
749 lyxerr[Debug::MATHED] << "LM_TK_STY not implemented\n";
750 //MathArray tmp = array;
751 //MathSizeInset * p = new MathSizeInset(MathStyles(yylval.l->id));
752 //array.push_back(p);
753 //mathed_parse_into(p->cell(0), FLAG_BRACE_FONT);
758 case LM_TK_DECORATION:
760 MathDecorationInset * p = new MathDecorationInset(yylval.l);
761 mathed_parse_into(p->cell(0), FLAG_ITEM);
771 array.push_back(new MathSymbolInset(yylval.l));
775 if (MathMacroTable::hasTemplate(yytext)) {
776 MathMacro * m = MathMacroTable::cloneTemplate(yytext);
777 for (int i = 0; i < m->nargs(); ++i)
778 mathed_parse_into(m->cell(i), FLAG_ITEM);
780 m->metrics(LM_ST_TEXT);
782 array.push_back(new MathFuncInset(yytext));
793 MathInsetTypes typ = latex_mathenv[i].typ;
795 if (typ == LM_OT_MATRIX) {
796 string const valign = lexArg('[') + 'c';
797 string const halign = lexArg('{');
798 //lyxerr << "valign: '" << valign << "'\n";
799 //lyxerr << "halign: '" << halign << "'\n";
800 MathArrayInset * m = new MathArrayInset(halign.size(), 1);
801 m->valign(valign[0]);
804 mathed_parse_lines(m, halign.size(), latex_mathenv[i].numbered, false);
806 //lyxerr << "read matrix " << *m << "\n";
809 lyxerr[Debug::MATHED] << "unknow math inset " << typ << "\n";
814 array.push_back(MathMacroTable::cloneTemplate(yylval.l->name));
818 curr_label = lexArg('{', true);
822 mathPrintError("Unrecognized token");
823 lyxerr[Debug::MATHED] << "[" << t << " " << yytext << "]" << endl;
826 } // end of big switch
828 if (flags & FLAG_LEAVE) {
829 flags &= ~FLAG_LEAVE;
834 lyxerr << " Math Panic, expect problems!" << endl;
835 // Search for the end command.
838 } while (yyis->good() && t != LM_TK_END && t);
849 MathArray mathed_parse_cell(string const & str)
851 istringstream is(str.c_str());
855 mathed_parse_into(ar, 0);
860 MathMacroTemplate * mathed_parse_macro(string const & str)
862 istringstream is(str.c_str());
863 return mathed_parse_macro(is);
867 MathMatrixInset * mathed_parse_normal(string const & str)
869 istringstream is(str.c_str());
870 return mathed_parse_normal(is);
875 MathMatrixInset * mathed_parse_normal(istream & is)
879 return mathed_parse_normal();
883 MathMacroTemplate * mathed_parse_macro(istream & is)
887 return mathed_parse_macro();
892 MathMatrixInset * mathed_parse_normal(LyXLex & lex)
894 yyis = &lex.getStream();
895 yylineno = lex.getLineNo();
897 MathMatrixInset * p = mathed_parse_normal();
899 // Update line number
900 lex.setLineNo(yylineno);
902 // reading of end_inset
905 if (lex.getString() == "\\end_inset")
907 lyxerr[Debug::MATHED] << "InsetFormula::Read: Garbage before \\end_inset,"
908 " or missing \\end_inset!" << endl;
914 MathMacroTemplate * mathed_parse_macro(LyXLex & lex)
916 yyis = &lex.getStream();
917 yylineno = lex.getLineNo();
919 MathMacroTemplate * p = mathed_parse_macro();
921 // Update line number
922 lex.setLineNo(yylineno);
924 // reading of end_inset
927 if (lex.getString() == "\\end_inset")
929 lyxerr[Debug::MATHED] << "InsetFormula::Read: Garbage before \\end_inset,"
930 " or missing \\end_inset!" << endl;