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_charinset.h"
31 #include "math_deliminset.h"
32 #include "math_factory.h"
33 #include "math_funcinset.h"
34 #include "math_macro.h"
35 #include "math_macrotable.h"
36 #include "math_macrotemplate.h"
37 #include "math_matrixinset.h"
38 #include "math_rootinset.h"
39 #include "math_scopeinset.h"
40 #include "math_sqrtinset.h"
41 #include "math_scriptinset.h"
42 #include "math_sqrtinset.h"
46 #include "support/lstrings.h"
54 MathScriptInset * prevScriptInset(MathArray const & array)
56 MathInset * p = array.back();
57 return (p && p->isScriptInset()) ? static_cast<MathScriptInset *>(p) : 0;
61 MathInset * lastScriptInset(MathArray & array, bool up, bool down, int limits)
63 MathScriptInset * p = prevScriptInset(array);
65 MathInset * b = array.back();
66 if (b && b->isScriptable()) {
67 p = new MathScriptInset(up, down, b->clone());
70 p = new MathScriptInset(up, down);
84 // These are lexical codes, not semantic
88 LexBOP, // Binary operators or relations
98 lexcode_enum lexcode[256];
101 const unsigned char LM_TK_OPEN = '{';
104 FLAG_BRACE = 1 << 0, // an opening brace needed
105 FLAG_BRACE_LAST = 1 << 1, // last closing brace ends the parsing process
106 FLAG_RIGHT = 1 << 2, // next right ends the parsing process
107 FLAG_END = 1 << 3, // next end ends the parsing process
108 FLAG_BRACK_END = 1 << 4, // next closing bracket ends the parsing process
109 FLAG_AMPERSAND = 1 << 5, // next & ends the parsing process
110 FLAG_NEWLINE = 1 << 6, // next \\ ends the parsing process
111 FLAG_ITEM = 1 << 7, // read a (possibly braced token)
112 FLAG_BLOCK = 1 << 8, // next block ends the parsing process
113 FLAG_LEAVE = 1 << 9, // marker for leaving the
117 struct latex_mathenv_type {
119 char const * basename;
125 latex_mathenv_type latex_mathenv[] = {
126 {"math", "math", LM_OT_SIMPLE, 0, 0},
127 {"equation*", "equation", LM_OT_EQUATION, 0, 0},
128 {"equation", "equation", LM_OT_EQUATION, 1, 0},
129 {"eqnarray*", "eqnarray", LM_OT_EQNARRAY, 0, 0},
130 {"eqnarray", "eqnarray", LM_OT_EQNARRAY, 1, 0},
131 {"align*", "align", LM_OT_ALIGN, 0, 1},
132 {"align", "align", LM_OT_ALIGN, 1, 1},
133 {"alignat*", "alignat", LM_OT_ALIGNAT, 0, 1},
134 {"alignat", "alignat", LM_OT_ALIGNAT, 1, 1},
135 {"multline*", "multline", LM_OT_MULTLINE, 0, 1},
136 {"multline", "multline", LM_OT_MULTLINE, 1, 1},
137 {"array", "array", LM_OT_MATRIX, 0, 1}
140 int const latex_mathenv_num = sizeof(latex_mathenv)/sizeof(latex_mathenv[0]);
146 for (int i = 0; i <= 255; ++i) {
148 lexcode[i] = LexOther;
150 lexcode[i] = LexSpace;
152 lexcode[i] = LexAlpha;
155 lexcode['\t'] = lexcode['\f'] = lexcode[' '] = LexSpace;
156 lexcode['\n'] = LexNewLine;
157 lexcode['%'] = LexComment;
158 lexcode['#'] = LexArgument;
159 lexcode['$'] = LexMath;
160 lexcode['+'] = lexcode['-'] = lexcode['*'] = lexcode['/']
161 = lexcode['<'] = lexcode['>'] = lexcode['='] = LexBOP;
163 lexcode['('] = lexcode[')'] = lexcode['|'] = lexcode['.'] =
164 lexcode['?'] = LexOther;
166 lexcode['\''] = lexcode['@'] = LexAlpha;
168 lexcode['['] = lexcode[']'] = lexcode['^'] = lexcode['_'] =
169 lexcode['&'] = LexSelf;
171 lexcode['{'] = LexSelf;
172 lexcode['}'] = LexSelf;
174 lexcode['\\'] = LexESC;
180 // Helper class for parsing
187 Parser(LyXLex & lex) : is_(lex.getStream()), lineno_(lex.getLineNo()) {}
189 Parser(istream & is) : is_(is), lineno_(0) {}
192 MathMacroTemplate * parse_macro();
194 MathMatrixInset * parse_normal();
196 void parse_into(MathArray & array, unsigned flags);
198 int lineno() const { return lineno_; }
204 string lexArg(unsigned char lf, bool accept_spaces = false);
206 unsigned char getuchar();
208 void error(string const & msg);
210 void parse_lines(MathGridInset * p, int col, bool numbered, bool outmost);
212 latexkeys const * read_delim();
223 latexkeys const * lval_;
236 unsigned char Parser::getuchar()
240 lyxerr << "The input stream is not well..." << endl;
242 return static_cast<unsigned char>(c);
246 string Parser::lexArg(unsigned char lf, bool accept_spaces = false)
261 unsigned char rg = 0;
262 if (lf == '{') rg = '}';
263 if (lf == '[') rg = ']';
264 if (lf == '(') rg = ')';
266 lyxerr[Debug::MATHED] << "Math parse error: unknown bracket '"
267 << lf << "'" << endl;
273 unsigned char c = getuchar();
278 if ((!isspace(c) || (c == ' ' && accept_spaces)) && depth > 0)
280 } while (depth > 0 && is_.good());
288 static bool init_done = false;
296 unsigned char c = getuchar();
297 //lyxerr << "reading byte: '" << c << "' code: " << lexcode[c] << endl;
299 if (lexcode[c] == LexNewLine) {
302 } else if (lexcode[c] == LexComment) {
305 } while (c != '\n' && is_.good()); // eat comments
306 } else if (lexcode[c] == LexOther) {
309 } else if (lexcode[c] == LexAlpha || lexcode[c] == LexSpace) {
312 } else if (lexcode[c] == LexBOP) {
315 } else if (lexcode[c] == LexMath) {
318 } else if (lexcode[c] == LexSelf) {
320 } else if (lexcode[c] == LexArgument) {
323 return LM_TK_ARGUMENT;
324 } else if (lexcode[c] == LexESC) {
326 //lyxerr << "reading second byte: '" << c << "' code: " << lexcode[c] << endl;
329 latexkeys const * l = in_word_set(s);
331 //lyxerr << "found key: " << l << endl;
332 //lyxerr << "found key name: " << l->name << endl;
333 //lyxerr << "found key token: " << l->token << endl;
338 if (lexcode[c] == LexAlpha) {
340 while (lexcode[c] == LexAlpha && is_.good()) {
344 while (lexcode[c] == LexSpace && is_.good())
346 if (lexcode[c] != LexSpace)
349 //lyxerr[Debug::MATHED] << "reading: text '" << sval_ << "'\n";
350 //lyxerr << "reading: text '" << sval_ << "'\n";
351 lval_ = in_word_set(sval_);
355 if (lval_->token == LM_TK_BEGIN || lval_->token == LM_TK_END) {
356 string name = lexArg('{');
358 while (i < latex_mathenv_num && name != latex_mathenv[i].name)
370 void Parser::error(string const & msg)
372 lyxerr << "Line ~" << lineno_ << ": Math parse error: " << msg << endl;
376 void Parser::parse_lines(MathGridInset * p, int col, bool numbered, bool outmost)
378 // save global variables
379 bool const saved_num = curr_num_;
380 string const saved_label = curr_label_;
382 for (int row = 0; true; ++row) {
383 // reset global variables
384 curr_num_ = numbered;
388 int idx = p->nargs() - p->ncols();
389 for (int i = 0; i < col - 1; ++i, ++idx)
390 parse_into(p->cell(idx), FLAG_AMPERSAND);
391 parse_into(p->cell(idx), FLAG_NEWLINE | FLAG_END);
394 MathMatrixInset * m = static_cast<MathMatrixInset *>(p);
395 m->numbered(row, curr_num_);
396 m->label(row, curr_label_);
397 if (curr_skip_.size()) {
398 m->vskip(LyXLength(curr_skip_), row);
413 // restore "global" variables
414 curr_num_ = saved_num;
415 curr_label_ = saved_label;
419 MathMacroTemplate * Parser::parse_macro()
421 if (yylex() != LM_TK_NEWCOMMAND) {
422 lyxerr << "\\newcommand expected\n";
426 string name = lexArg('{').substr(1);
427 string arg = lexArg('[');
428 int narg = arg.empty() ? 0 : atoi(arg.c_str());
429 MathMacroTemplate * p = new MathMacroTemplate(name, narg);
430 parse_into(p->cell(0), FLAG_BRACE | FLAG_BRACE_LAST);
435 MathMatrixInset * Parser::parse_normal()
437 MathMatrixInset * p = 0;
444 lyxerr[Debug::MATHED]
445 << "reading math environment " << i << " "
446 << latex_mathenv[i].name << "\n";
448 MathInsetTypes typ = latex_mathenv[i].typ;
449 p = new MathMatrixInset(typ);
454 curr_num_ = latex_mathenv[i].numbered;
456 parse_into(p->cell(0), 0);
457 p->numbered(0, curr_num_);
458 p->label(0, curr_label_);
462 case LM_OT_EQUATION: {
463 curr_num_ = latex_mathenv[i].numbered;
465 parse_into(p->cell(0), FLAG_END);
466 p->numbered(0, curr_num_);
467 p->label(0, curr_label_);
471 case LM_OT_EQNARRAY: {
472 parse_lines(p, 3, latex_mathenv[i].numbered, true);
477 p->halign(lexArg('{'));
478 parse_lines(p, 2, latex_mathenv[i].numbered, true);
482 case LM_OT_ALIGNAT: {
483 p->halign(lexArg('{'));
484 parse_lines(p, 2, latex_mathenv[i].numbered, true);
489 lyxerr[Debug::MATHED]
490 << "1: unknown math environment: " << typ << "\n";
497 lyxerr[Debug::MATHED]
498 << "2 unknown math environment: " << t << "\n";
505 latexkeys const * Parser::read_delim()
508 //lyxerr << "found symbol: " << ld << "\n";
509 latexkeys const * l = in_word_set(".");
516 //lyxerr << "found key 1: '" << l << "'\n";
517 //lyxerr << "found key 1: '" << l->name << "'\n";
525 //lyxerr << "found key 2: '" << l->name << "'\n";
532 //lyxerr << "found key 2: '" << l->name << "'\n";
539 void Parser::parse_into(MathArray & array, unsigned flags)
541 MathTextCodes yyvarcode = LM_TC_VAR;
548 //lyxerr << "t: " << t << " flags: " << flags << " i: " << ival_
549 // << " '" << sval_ << "'\n";
550 //array.dump(lyxerr);
553 if (flags & FLAG_ITEM) {
555 if (t == LM_TK_OPEN) {
556 // skip the brace and collect everything to the next matching
558 flags |= FLAG_BRACE_LAST;
561 // take only this single token
566 if (flags & FLAG_BRACE) {
567 if (t != LM_TK_OPEN) {
568 error("Expected {. Maybe you forgot to enclose an argument in {}");
572 flags &= ~FLAG_BRACE;
585 if (!isspace(ival_) || yyvarcode == LM_TC_TEXTRM)
586 array.push_back(new MathCharInset(ival_, yyvarcode));
589 case LM_TK_ARGUMENT: {
590 MathMacroArgument * p = new MathMacroArgument(ival_);
591 //p->code(yyvarcode);
597 array.push_back(new MathCharInset(ival_, LM_TC_SPECIAL));
601 array.push_back(new MathCharInset(ival_, LM_TC_CONST));
605 //lyxerr << " creating ScopeInset\n";
606 array.push_back(new MathScopeInset);
607 parse_into(array.back()->cell(0), FLAG_BRACE_LAST);
611 if (flags & FLAG_BRACE_LAST)
616 array.push_back(new MathCharInset('[', LM_TC_CONST));
620 if (flags & FLAG_BRACK_END)
623 array.push_back(new MathCharInset(']', LM_TC_CONST));
628 lastScriptInset(array, true, false, limits)->cell(0), FLAG_ITEM);
633 lastScriptInset(array, false, true, limits)->cell(1), FLAG_ITEM);
638 //lyxerr << "setting limit to " << limits << "\n";
642 if (flags & FLAG_AMPERSAND) {
643 flags &= ~FLAG_AMPERSAND;
646 lyxerr[Debug::MATHED]
647 << "found tab unexpectedly, array: '" << array << "'\n";
652 curr_skip_ = lexArg('[');
653 if (flags & FLAG_NEWLINE) {
654 flags &= ~FLAG_NEWLINE;
657 lyxerr[Debug::MATHED]
658 << "found newline unexpectedly, array: '" << array << "'\n";
666 array.push_back(new MathCharInset(ival_, LM_TC_BOP));
671 unsigned char c = getuchar();
673 array.push_back(new MathRootInset);
674 parse_into(array.back()->cell(0), FLAG_BRACK_END);
675 parse_into(array.back()->cell(1), FLAG_ITEM);
678 array.push_back(new MathSqrtInset);
679 parse_into(array.back()->cell(0), FLAG_ITEM);
686 latexkeys const * l = read_delim();
688 parse_into(ar, FLAG_RIGHT);
689 latexkeys const * r = read_delim();
690 MathDelimInset * dl = new MathDelimInset(l, r);
697 if (flags & FLAG_RIGHT)
699 error("Unmatched right delimiter");
705 MathTextCodes t = static_cast<MathTextCodes>(lval_->id);
707 parse_into(ar, FLAG_ITEM);
708 for (MathArray::iterator it = ar.begin(); it != ar.end(); ++it)
709 (*it)->handleFont(t);
715 yyvarcode = static_cast<MathTextCodes>(lval_->id);
720 lyxerr[Debug::MATHED] << "LM_TK_STY not implemented\n";
721 //MathArray tmp = array;
722 //MathSizeInset * p = new MathSizeInset(MathStyles(lval_->id));
723 //array.push_back(p);
724 //parse_into(p->cell(0), FLAG_BRACE_FONT);
733 if (MathMacroTable::hasTemplate(sval_)) {
734 MathMacro * m = MathMacroTable::cloneTemplate(sval_);
735 for (int i = 0; i < m->nargs(); ++i)
736 parse_into(m->cell(i), FLAG_ITEM);
738 m->metrics(LM_ST_TEXT);
740 array.push_back(new MathFuncInset(sval_));
746 MathInsetTypes typ = latex_mathenv[i].typ;
748 if (typ == LM_OT_MATRIX) {
749 string const valign = lexArg('[') + 'c';
750 string const halign = lexArg('{');
751 //lyxerr << "valign: '" << valign << "'\n";
752 //lyxerr << "halign: '" << halign << "'\n";
753 MathArrayInset * m = new MathArrayInset(halign.size(), 1);
754 m->valign(valign[0]);
757 parse_lines(m, halign.size(), latex_mathenv[i].numbered, false);
759 //lyxerr << "read matrix " << *m << "\n";
762 lyxerr[Debug::MATHED] << "unknow math inset " << typ << "\n";
767 curr_label_ = lexArg('{', true);
773 parse_into(ar, FLAG_BLOCK);
779 MathInset * p = createMathInset(lval_);
781 for (int i = 0; i < p->nargs(); ++i)
782 parse_into(p->cell(i), FLAG_ITEM);
785 error("Unrecognized token");
786 //lyxerr[Debug::MATHED] << "[" << t << " " << sval_ << "]\n";
787 lyxerr << "[" << t << " " << sval_ << "]\n";
790 } // end of big switch
792 if (flags & FLAG_LEAVE) {
793 flags &= ~FLAG_LEAVE;
798 lyxerr << " Math Panic, expect problems!\n";
799 // Search for the end command.
802 } while (is_.good() && t != LM_TK_END && t);
810 void parse_end(LyXLex & lex, int lineno)
812 // Update line number
813 lex.setLineNo(lineno);
815 // reading of end_inset
818 if (lex.getString() == "\\end_inset")
820 //lyxerr[Debug::MATHED] << "InsetFormula::Read: Garbage before \\end_inset,"
821 lyxerr << "InsetFormula::Read: Garbage before \\end_inset,"
822 " or missing \\end_inset!\n";
826 } // anonymous namespace
830 MathArray mathed_parse_cell(string const & str)
832 istringstream is(str.c_str());
835 parser.parse_into(ar, 0);
841 MathMacroTemplate * mathed_parse_macro(string const & str)
843 istringstream is(str.c_str());
845 return parser.parse_macro();
848 MathMacroTemplate * mathed_parse_macro(istream & is)
851 return parser.parse_macro();
854 MathMacroTemplate * mathed_parse_macro(LyXLex & lex)
857 MathMacroTemplate * p = parser.parse_macro();
858 parse_end(lex, parser.lineno());
864 MathMatrixInset * mathed_parse_normal(string const & str)
866 istringstream is(str.c_str());
868 return parser.parse_normal();
871 MathMatrixInset * mathed_parse_normal(istream & is)
874 return parser.parse_normal();
877 MathMatrixInset * mathed_parse_normal(LyXLex & lex)
880 MathMatrixInset * p = parser.parse_normal();
881 parse_end(lex, parser.lineno());