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.
23 #pragma implementation
26 #include "math_parser.h"
28 #include "math_inset.h"
29 #include "math_arrayinset.h"
30 #include "math_bigopinset.h"
31 #include "math_charinset.h"
32 #include "math_dotsinset.h"
33 #include "math_decorationinset.h"
34 #include "math_deliminset.h"
35 #include "math_fracinset.h"
36 #include "math_funcinset.h"
37 #include "math_funcliminset.h"
38 #include "math_macro.h"
39 #include "math_macrotable.h"
40 #include "math_macrotemplate.h"
41 #include "math_matrixinset.h"
42 #include "math_noglyphinset.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"
61 MathScriptInset * prevScriptInset(MathArray const & array)
63 MathInset * p = array.back();
64 return (p && p->isScriptInset()) ? static_cast<MathScriptInset *>(p) : 0;
68 MathInset * lastScriptInset(MathArray & array, bool up, bool down, int limits)
70 MathScriptInset * p = prevScriptInset(array);
72 MathInset * b = array.back();
73 if (b && b->isScriptable()) {
74 p = new MathScriptInset(up, down, b->clone());
77 p = new MathScriptInset(up, down);
91 // These are lexical codes, not semantic
96 LexBOP, // Binary operators or relations
108 lexcode_enum lexcode[256];
111 const unsigned char LM_TK_OPEN = '{';
112 const unsigned char LM_TK_CLOSE = '}';
115 FLAG_BRACE = 1 << 0, // A { needed //}
116 FLAG_BRACE_LAST = 1 << 1, // // { Last } ends the parsing process
117 FLAG_RIGHT = 1 << 2, // Next right ends the parsing process
118 FLAG_END = 1 << 3, // Next end ends the parsing process
119 FLAG_BRACE_FONT = 1 << 4, // // { Next } closes a font
120 FLAG_BRACK_END = 1 << 5, // // [ Next ] ends the parsing process
121 FLAG_AMPERSAND = 1 << 6, // Next & ends the parsing process
122 FLAG_NEWLINE = 1 << 7, // Next \\ ends the parsing process
123 FLAG_ITEM = 1 << 8, // read a (possibly braced token)
124 FLAG_LEAVE = 1 << 9, // marker for leaving the
125 FLAG_OPTARG = 1 << 10 // reads an argument in []
129 struct latex_mathenv_type {
131 char const * basename;
137 latex_mathenv_type latex_mathenv[] = {
138 {"math", "math", LM_OT_SIMPLE, 0, 0},
139 {"equation*", "equation", LM_OT_EQUATION, 0, 0},
140 {"equation", "equation", LM_OT_EQUATION, 1, 0},
141 {"eqnarray*", "eqnarray", LM_OT_EQNARRAY, 0, 0},
142 {"eqnarray", "eqnarray", LM_OT_EQNARRAY, 1, 0},
143 {"align*", "align", LM_OT_ALIGN, 0, 1},
144 {"align", "align", LM_OT_ALIGN, 1, 1},
145 {"alignat*", "alignat", LM_OT_ALIGNAT, 0, 1},
146 {"alignat", "alignat", LM_OT_ALIGNAT, 1, 1},
147 {"multline*", "multline", LM_OT_MULTLINE, 0, 1},
148 {"multline", "multline", LM_OT_MULTLINE, 1, 1},
149 {"array", "array", LM_OT_MATRIX, 0, 1}
152 int const latex_mathenv_num = sizeof(latex_mathenv)/sizeof(latex_mathenv[0]);
158 for (int i = 0; i <= 255; ++i) {
160 lexcode[i] = LexOther;
162 lexcode[i] = LexSpace;
164 lexcode[i] = LexAlpha;
167 lexcode['\t'] = lexcode['\f'] = lexcode[' '] = LexSpace;
168 lexcode['\n'] = LexNewLine;
169 lexcode['%'] = LexComment;
170 lexcode['#'] = LexArgument;
171 lexcode['$'] = LexMath;
172 lexcode['+'] = lexcode['-'] = lexcode['*'] = lexcode['/']
173 = lexcode['<'] = lexcode['>'] = lexcode['='] = LexBOP;
175 lexcode['('] = lexcode[')'] = lexcode['|'] = lexcode['.'] =
176 lexcode['?'] = LexOther;
178 lexcode['\''] = lexcode['@'] = LexAlpha;
180 lexcode['['] = lexcode[']'] = lexcode['^'] = lexcode['_'] =
181 lexcode['&'] = LexSelf;
183 lexcode['\\'] = LexESC;
184 lexcode['{'] = LexOpen;
185 lexcode['}'] = LexClose;
191 // Helper class for parsing
198 Parser(LyXLex & lex) : is_(lex.getStream()), lineno_(lex.getLineNo()) {}
200 Parser(istream & is) : is_(is), lineno_(0) {}
203 MathMacroTemplate * parse_macro();
205 MathMatrixInset * parse_normal();
207 void parse_into(MathArray & array, unsigned flags);
209 int lineno() const { return lineno_; }
215 string lexArg(unsigned char lf, bool accept_spaces = false);
217 unsigned char getuchar();
219 void error(string const & msg);
221 void parse_lines(MathGridInset * p, int col, bool numbered, bool outmost);
223 latexkeys const * read_delim();
234 latexkeys const * lval_;
245 unsigned char Parser::getuchar()
250 lyxerr << "The input stream is not well..." << endl;
251 return static_cast<unsigned char>(c);
255 string Parser::lexArg(unsigned char lf, bool accept_spaces = false)
270 unsigned char rg = 0;
271 if (lf == '{') rg = '}';
272 if (lf == '[') rg = ']';
273 if (lf == '(') rg = ')';
275 lyxerr[Debug::MATHED] << "Math parse error: unknown bracket '"
276 << lf << "'" << endl;
282 unsigned char c = getuchar();
287 if ((!isspace(c) || (c == ' ' && accept_spaces)) && depth > 0)
289 } while (depth > 0 && is_.good());
297 static bool init_done = false;
305 unsigned char c = getuchar();
306 lyxerr << "reading byte: '" << c << "' code: " << lexcode[c] << endl;
308 if (lexcode[c] == LexNewLine) {
311 } else if (lexcode[c] == LexComment) {
314 } while (c != '\n' && is_.good()); // eat comments
315 } else if (lexcode[c] == LexOther) {
318 } else if (lexcode[c] == LexAlpha || lexcode[c] == LexSpace) {
321 } else if (lexcode[c] == LexBOP) {
324 } else if (lexcode[c] == LexMath) {
327 } else if (lexcode[c] == LexSelf) {
329 } else if (lexcode[c] == LexArgument) {
332 return LM_TK_ARGUMENT;
333 } else if (lexcode[c] == LexOpen) {
335 } else if (lexcode[c] == LexClose) {
337 } else if (lexcode[c] == LexESC) {
339 //lyxerr << "reading second byte: '" << c << "' code: " << lexcode[c] << endl;
342 latexkeys const * l = in_word_set(s);
344 //lyxerr << "found key: " << l << endl;
345 //lyxerr << "found key name: " << l->name << endl;
346 //lyxerr << "found key token: " << l->token << endl;
351 if (lexcode[c] == LexAlpha) {
353 while (lexcode[c] == LexAlpha && is_.good()) {
357 while (lexcode[c] == LexSpace && is_.good())
359 if (lexcode[c] != LexSpace)
362 //lyxerr[Debug::MATHED] << "reading: text '" << sval_ << "'\n";
363 //lyxerr << "reading: text '" << sval_ << "'\n";
364 latexkeys const * l = in_word_set(sval_);
368 if (l->token == LM_TK_BEGIN || l->token == LM_TK_END) {
369 string name = lexArg('{');
371 while (i < latex_mathenv_num && name != latex_mathenv[i].name)
374 } else if (l->token == LM_TK_SPACE)
386 void Parser::error(string const & msg)
388 lyxerr << "Line ~" << lineno_ << ": Math parse error: " << msg << endl;
392 void Parser::parse_lines(MathGridInset * p, int col, bool numbered, bool outmost)
394 // save global variables
395 bool const saved_num = curr_num_;
396 string const saved_label = curr_label_;
398 for (int row = 0; true; ++row) {
399 // reset global variables
400 curr_num_ = numbered;
404 int idx = p->nargs() - p->ncols();
405 for (int i = 0; i < col - 1; ++i, ++idx)
406 parse_into(p->cell(idx), FLAG_AMPERSAND);
407 parse_into(p->cell(idx), FLAG_NEWLINE | FLAG_END);
410 MathMatrixInset * m = static_cast<MathMatrixInset *>(p);
411 m->numbered(row, curr_num_);
412 m->label(row, curr_label_);
425 // restore "global" variables
426 curr_num_ = saved_num;
427 curr_label_ = saved_label;
431 MathMacroTemplate * Parser::parse_macro()
433 if (yylex() != LM_TK_NEWCOMMAND) {
434 lyxerr << "\\newcommand expected\n";
438 string name = lexArg('{').substr(1);
439 string arg = lexArg('[');
440 int narg = arg.empty() ? 0 : atoi(arg.c_str());
441 MathMacroTemplate * p = new MathMacroTemplate(name, narg);
442 parse_into(p->cell(0), FLAG_BRACE | FLAG_BRACE_LAST);
447 MathMatrixInset * Parser::parse_normal()
449 MathMatrixInset * p = 0;
456 lyxerr[Debug::MATHED]
457 << "reading math environment " << i << " "
458 << latex_mathenv[i].name << "\n";
460 MathInsetTypes typ = latex_mathenv[i].typ;
461 p = new MathMatrixInset(typ);
466 curr_num_ = latex_mathenv[i].numbered;
468 parse_into(p->cell(0), 0);
469 p->numbered(0, curr_num_);
470 p->label(0, curr_label_);
474 case LM_OT_EQUATION: {
475 curr_num_ = latex_mathenv[i].numbered;
477 parse_into(p->cell(0), FLAG_END);
478 p->numbered(0, curr_num_);
479 p->label(0, curr_label_);
483 case LM_OT_EQNARRAY: {
484 parse_lines(p, 3, latex_mathenv[i].numbered, true);
489 p->halign(lexArg('{'));
490 parse_lines(p, 2, latex_mathenv[i].numbered, true);
494 case LM_OT_ALIGNAT: {
495 p->halign(lexArg('{'));
496 parse_lines(p, 2, latex_mathenv[i].numbered, true);
501 lyxerr[Debug::MATHED]
502 << "1: unknown math environment: " << typ << "\n";
509 lyxerr[Debug::MATHED]
510 << "2 unknown math environment: " << t << "\n";
517 latexkeys const * Parser::read_delim()
520 //lyxerr << "found symbol: " << ld << "\n";
521 latexkeys const * l = in_word_set(".");
528 //lyxerr << "found key 1: '" << l << "'\n";
529 //lyxerr << "found key 1: '" << l->name << "'\n";
537 //lyxerr << "found key 2: '" << l->name << "'\n";
544 //lyxerr << "found key 2: '" << l->name << "'\n";
551 void Parser::parse_into(MathArray & array, unsigned flags)
553 static int plevel = -1;
556 MathTextCodes yyvarcode = LM_TC_VAR;
564 //lyxerr << "t: " << t << " flags: " << flags << " i: " << ival_
565 // << " '" << sval_ << "'\n";
566 //array.dump(lyxerr);
569 if (flags & FLAG_ITEM) {
571 if (t == LM_TK_OPEN) {
572 // skip the brace and regard everything to the next matching
576 flags |= FLAG_BRACE_LAST;
578 // regard only this single token
583 if ((flags & FLAG_BRACE) && t != LM_TK_OPEN) {
585 "Expected {. Maybe you forgot to enclose an argument in {}");
593 if (!isspace(ival_) || yyvarcode == LM_TC_TEXTRM)
594 array.push_back(new MathCharInset(ival_, yyvarcode));
597 case LM_TK_ARGUMENT: {
598 MathMacroArgument * p = new MathMacroArgument(ival_);
605 array.push_back(new MathCharInset(ival_, LM_TC_SPECIAL));
609 array.push_back(new MathCharInset(ival_, LM_TC_CONST));
614 if (flags & FLAG_BRACE)
615 flags &= ~FLAG_BRACE;
617 array.push_back(new MathCharInset('{', LM_TC_TEX));
623 error("Unmatching braces");
627 if (flags & FLAG_BRACE_FONT) {
628 yyvarcode = LM_TC_VAR;
629 flags &= ~FLAG_BRACE_FONT;
632 if (brace == 0 && (flags & FLAG_BRACE_LAST))
635 array.push_back(new MathCharInset('}', LM_TC_TEX));
639 array.push_back(new MathCharInset('[', LM_TC_CONST));
643 if (flags & FLAG_BRACK_END)
646 array.push_back(new MathCharInset(']', LM_TC_CONST));
651 lastScriptInset(array, true, false, limits)->cell(0), FLAG_ITEM);
656 lastScriptInset(array, false, true, limits)->cell(1), FLAG_ITEM);
661 //lyxerr << "setting limit to " << limits << "\n";
665 if (flags & FLAG_AMPERSAND) {
666 flags &= ~FLAG_AMPERSAND;
670 lyxerr[Debug::MATHED]
671 << "found tab unexpectedly, array: '" << array << "'\n";
676 lexArg('['); // ignore things like \\[5pt] for a while
677 if (flags & FLAG_NEWLINE) {
678 flags &= ~FLAG_NEWLINE;
682 lyxerr[Debug::MATHED]
683 << "found newline unexpectedly, array: '" << array << "'\n";
693 array.push_back(new MathNoglyphInset(lval_));
698 array.push_back(new MathBigopInset(lval_));
703 array.push_back(new MathFuncLimInset(lval_));
708 array.push_back(new MathSymbolInset(lval_));
712 array.push_back(new MathCharInset(ival_, LM_TC_BOP));
717 array.push_back(new MathSpaceInset(ival_));
721 array.push_back(new MathDotsInset(lval_));
726 MathStackrelInset * p = new MathStackrelInset;
727 parse_into(p->cell(0), FLAG_ITEM);
728 parse_into(p->cell(1), FLAG_ITEM);
735 MathFracInset * p = new MathFracInset;
736 parse_into(p->cell(0), FLAG_ITEM);
737 parse_into(p->cell(1), FLAG_ITEM);
744 unsigned char c = getuchar();
746 array.push_back(new MathRootInset);
747 parse_into(array.back()->cell(0), FLAG_BRACK_END);
748 parse_into(array.back()->cell(1), FLAG_ITEM);
751 array.push_back(new MathSqrtInset);
752 parse_into(array.back()->cell(0), FLAG_ITEM);
759 latexkeys const * l = read_delim();
761 parse_into(ar, FLAG_RIGHT);
762 latexkeys const * r = read_delim();
763 MathDelimInset * dl = new MathDelimInset(l, r);
770 if (flags & FLAG_RIGHT) {
774 error("Unmatched right delimiter");
779 yyvarcode = static_cast<MathTextCodes>(lval_->id);
780 flags |= (FLAG_BRACE | FLAG_BRACE_FONT);
785 lyxerr[Debug::MATHED] << "LM_TK_STY not implemented\n";
786 //MathArray tmp = array;
787 //MathSizeInset * p = new MathSizeInset(MathStyles(lval_->id));
788 //array.push_back(p);
789 //parse_into(p->cell(0), FLAG_BRACE_FONT);
793 case LM_TK_DECORATION:
795 MathDecorationInset * p = new MathDecorationInset(lval_);
796 parse_into(p->cell(0), FLAG_ITEM);
806 array.push_back(new MathSymbolInset(lval_));
810 if (MathMacroTable::hasTemplate(sval_)) {
811 MathMacro * m = MathMacroTable::cloneTemplate(sval_);
812 for (int i = 0; i < m->nargs(); ++i)
813 parse_into(m->cell(i), FLAG_ITEM);
815 m->metrics(LM_ST_TEXT);
817 array.push_back(new MathFuncInset(sval_));
828 MathInsetTypes typ = latex_mathenv[i].typ;
830 if (typ == LM_OT_MATRIX) {
831 string const valign = lexArg('[') + 'c';
832 string const halign = lexArg('{');
833 //lyxerr << "valign: '" << valign << "'\n";
834 //lyxerr << "halign: '" << halign << "'\n";
835 MathArrayInset * m = new MathArrayInset(halign.size(), 1);
836 m->valign(valign[0]);
839 parse_lines(m, halign.size(), latex_mathenv[i].numbered, false);
841 //lyxerr << "read matrix " << *m << "\n";
844 lyxerr[Debug::MATHED] << "unknow math inset " << typ << "\n";
849 array.push_back(MathMacroTable::cloneTemplate(lval_->name));
853 curr_label_ = lexArg('{', true);
857 error("Unrecognized token");
858 lyxerr[Debug::MATHED] << "[" << t << " " << sval_ << "]" << endl;
861 } // end of big switch
863 if (flags & FLAG_LEAVE) {
864 flags &= ~FLAG_LEAVE;
869 lyxerr << " Math Panic, expect problems!" << endl;
870 // Search for the end command.
873 } while (is_.good() && t != LM_TK_END && t);
882 void parse_end(LyXLex & lex, int lineno)
884 // Update line number
885 lex.setLineNo(lineno);
887 // reading of end_inset
890 if (lex.getString() == "\\end_inset")
892 lyxerr[Debug::MATHED] << "InsetFormula::Read: Garbage before \\end_inset,"
893 " or missing \\end_inset!" << endl;
897 } // anonymous namespace
901 MathArray mathed_parse_cell(string const & str)
903 istringstream is(str.c_str());
906 parser.parse_into(ar, 0);
912 MathMacroTemplate * mathed_parse_macro(string const & str)
914 istringstream is(str.c_str());
916 return parser.parse_macro();
919 MathMacroTemplate * mathed_parse_macro(istream & is)
922 return parser.parse_macro();
925 MathMacroTemplate * mathed_parse_macro(LyXLex & lex)
928 MathMacroTemplate * p = parser.parse_macro();
929 parse_end(lex, parser.lineno());
935 MathMatrixInset * mathed_parse_normal(string const & str)
937 istringstream is(str.c_str());
939 return parser.parse_normal();
942 MathMatrixInset * mathed_parse_normal(istream & is)
945 return parser.parse_normal();
948 MathMatrixInset * mathed_parse_normal(LyXLex & lex)
951 MathMatrixInset * p = parser.parse_normal();
952 parse_end(lex, parser.lineno());