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 = '{';
102 const unsigned char LM_TK_CLOSE = '}';
105 FLAG_BRACE = 1 << 0, // an opening brace needed
106 FLAG_BRACE_LAST = 1 << 1, // last closing brace ends the parsing process
107 FLAG_RIGHT = 1 << 2, // next right ends the parsing process
108 FLAG_END = 1 << 3, // next end ends the parsing process
109 FLAG_BRACK_END = 1 << 4, // next closing bracket ends the parsing process
110 FLAG_AMPERSAND = 1 << 5, // next & ends the parsing process
111 FLAG_NEWLINE = 1 << 6, // next \\ ends the parsing process
112 FLAG_ITEM = 1 << 7, // read a (possibly braced token)
113 FLAG_BLOCK = 1 << 8, // next block ends the parsing process
114 FLAG_LEAVE = 1 << 9, // marker for leaving the
118 struct latex_mathenv_type {
120 char const * basename;
126 latex_mathenv_type latex_mathenv[] = {
127 {"math", "math", LM_OT_SIMPLE, 0, 0},
128 {"equation*", "equation", LM_OT_EQUATION, 0, 0},
129 {"equation", "equation", LM_OT_EQUATION, 1, 0},
130 {"eqnarray*", "eqnarray", LM_OT_EQNARRAY, 0, 0},
131 {"eqnarray", "eqnarray", LM_OT_EQNARRAY, 1, 0},
132 {"align*", "align", LM_OT_ALIGN, 0, 1},
133 {"align", "align", LM_OT_ALIGN, 1, 1},
134 {"alignat*", "alignat", LM_OT_ALIGNAT, 0, 1},
135 {"alignat", "alignat", LM_OT_ALIGNAT, 1, 1},
136 {"multline*", "multline", LM_OT_MULTLINE, 0, 1},
137 {"multline", "multline", LM_OT_MULTLINE, 1, 1},
138 {"array", "array", LM_OT_MATRIX, 0, 1}
141 int const latex_mathenv_num = sizeof(latex_mathenv)/sizeof(latex_mathenv[0]);
147 for (int i = 0; i <= 255; ++i) {
149 lexcode[i] = LexOther;
151 lexcode[i] = LexSpace;
153 lexcode[i] = LexAlpha;
156 lexcode['\t'] = lexcode['\f'] = lexcode[' '] = LexSpace;
157 lexcode['\n'] = LexNewLine;
158 lexcode['%'] = LexComment;
159 lexcode['#'] = LexArgument;
160 lexcode['$'] = LexMath;
161 lexcode['+'] = lexcode['-'] = lexcode['*'] = lexcode['/']
162 = lexcode['<'] = lexcode['>'] = lexcode['='] = LexBOP;
164 lexcode['('] = lexcode[')'] = lexcode['|'] = lexcode['.'] =
165 lexcode['?'] = LexOther;
167 lexcode['\''] = lexcode['@'] = LexAlpha;
169 lexcode['['] = lexcode[']'] = lexcode['^'] = lexcode['_'] =
170 lexcode['&'] = LexSelf;
172 lexcode['{'] = LexSelf;
173 lexcode['}'] = LexSelf;
175 lexcode['\\'] = LexESC;
181 // Helper class for parsing
189 : is_(lex.getStream()), lineno_(lex.getLineNo()), putback_token_(0)
193 : is_(is), lineno_(0), putback_token_(0)
197 MathMacroTemplate * parse_macro();
199 MathMatrixInset * parse_normal();
201 void parse_into(MathArray & array, unsigned flags);
203 int lineno() const { return lineno_; }
205 void putback(int token);
211 string lexArg(unsigned char lf, bool accept_spaces = false);
213 unsigned char getuchar();
215 void error(string const & msg);
217 void parse_lines(MathGridInset * p, int col, bool numbered, bool outmost);
219 latexkeys const * read_delim();
230 latexkeys const * lval_;
246 void Parser::putback(int token)
248 putback_token_ = token;
252 unsigned char Parser::getuchar()
256 lyxerr << "The input stream is not well..." << endl;
258 return static_cast<unsigned char>(c);
262 string Parser::lexArg(unsigned char lf, bool accept_spaces = false)
277 unsigned char rg = 0;
278 if (lf == '{') rg = '}';
279 if (lf == '[') rg = ']';
280 if (lf == '(') rg = ')';
282 lyxerr[Debug::MATHED] << "Math parse error: unknown bracket '"
283 << lf << "'" << endl;
289 unsigned char c = getuchar();
294 if ((!isspace(c) || (c == ' ' && accept_spaces)) && depth > 0)
296 } while (depth > 0 && is_.good());
304 static bool init_done = false;
311 if (putback_token_) {
312 int token = putback_token_;
318 unsigned char c = getuchar();
319 //lyxerr << "reading byte: '" << c << "' code: " << lexcode[c] << endl;
321 if (lexcode[c] == LexNewLine) {
326 if (lexcode[c] == LexComment) {
329 } while (c != '\n' && is_.good()); // eat comments
332 if (lexcode[c] == LexOther) {
337 if (lexcode[c] == LexAlpha || lexcode[c] == LexSpace) {
342 if (lexcode[c] == LexBOP) {
347 if (lexcode[c] == LexMath) {
352 if (lexcode[c] == LexSelf) {
356 if (lexcode[c] == LexArgument) {
359 return LM_TK_ARGUMENT;
362 if (lexcode[c] == LexESC) {
364 //lyxerr << "reading second byte: '" << c << "' code: " << lexcode[c] << endl;
367 latexkeys const * l = in_word_set(s);
369 //lyxerr << "found key: " << l << endl;
370 //lyxerr << "found key name: " << l->name << endl;
371 //lyxerr << "found key token: " << l->token << endl;
376 if (lexcode[c] == LexAlpha) {
378 while (lexcode[c] == LexAlpha && is_.good()) {
382 while (lexcode[c] == LexSpace && is_.good())
384 if (lexcode[c] != LexSpace)
387 //lyxerr[Debug::MATHED] << "reading: text '" << sval_ << "'\n";
388 //lyxerr << "reading: text '" << sval_ << "'\n";
389 lval_ = in_word_set(sval_);
393 if (lval_->token == LM_TK_BEGIN || lval_->token == LM_TK_END) {
394 string name = lexArg('{');
396 while (i < latex_mathenv_num && name != latex_mathenv[i].name)
408 void Parser::error(string const & msg)
410 lyxerr << "Line ~" << lineno_ << ": Math parse error: " << msg << endl;
414 void Parser::parse_lines(MathGridInset * p, int col, bool numbered, bool outmost)
416 // save global variables
417 bool const saved_num = curr_num_;
418 string const saved_label = curr_label_;
420 for (int row = 0; true; ++row) {
421 // reset global variables
422 curr_num_ = numbered;
426 int idx = p->nargs() - p->ncols();
427 for (int i = 0; i < col - 1; ++i, ++idx)
428 parse_into(p->cell(idx), FLAG_AMPERSAND);
429 parse_into(p->cell(idx), FLAG_NEWLINE | FLAG_END);
432 MathMatrixInset * m = static_cast<MathMatrixInset *>(p);
433 m->numbered(row, curr_num_);
434 m->label(row, curr_label_);
435 if (curr_skip_.size()) {
436 m->vskip(LyXLength(curr_skip_), row);
451 // restore "global" variables
452 curr_num_ = saved_num;
453 curr_label_ = saved_label;
457 MathMacroTemplate * Parser::parse_macro()
459 if (yylex() != LM_TK_NEWCOMMAND) {
460 lyxerr << "\\newcommand expected\n";
464 string name = lexArg('{').substr(1);
465 string arg = lexArg('[');
466 int narg = arg.empty() ? 0 : atoi(arg.c_str());
467 MathMacroTemplate * p = new MathMacroTemplate(name, narg);
468 parse_into(p->cell(0), FLAG_BRACE | FLAG_BRACE_LAST);
473 MathMatrixInset * Parser::parse_normal()
475 MathMatrixInset * p = 0;
482 lyxerr[Debug::MATHED]
483 << "reading math environment " << i << " "
484 << latex_mathenv[i].name << "\n";
486 MathInsetTypes typ = latex_mathenv[i].typ;
487 p = new MathMatrixInset(typ);
492 curr_num_ = latex_mathenv[i].numbered;
494 parse_into(p->cell(0), 0);
495 p->numbered(0, curr_num_);
496 p->label(0, curr_label_);
500 case LM_OT_EQUATION: {
501 curr_num_ = latex_mathenv[i].numbered;
503 parse_into(p->cell(0), FLAG_END);
504 p->numbered(0, curr_num_);
505 p->label(0, curr_label_);
509 case LM_OT_EQNARRAY: {
510 parse_lines(p, 3, latex_mathenv[i].numbered, true);
515 p->halign(lexArg('{'));
516 parse_lines(p, 2, latex_mathenv[i].numbered, true);
520 case LM_OT_ALIGNAT: {
521 p->halign(lexArg('{'));
522 parse_lines(p, 2, latex_mathenv[i].numbered, true);
527 lyxerr[Debug::MATHED]
528 << "1: unknown math environment: " << typ << "\n";
535 lyxerr[Debug::MATHED]
536 << "2 unknown math environment: " << t << "\n";
543 latexkeys const * Parser::read_delim()
546 //lyxerr << "found symbol: " << ld << "\n";
547 latexkeys const * l = in_word_set(".");
554 //lyxerr << "found key 1: '" << l << "'\n";
555 //lyxerr << "found key 1: '" << l->name << "'\n";
563 //lyxerr << "found key 2: '" << l->name << "'\n";
570 //lyxerr << "found key 2: '" << l->name << "'\n";
577 void Parser::parse_into(MathArray & array, unsigned flags)
579 MathTextCodes yyvarcode = LM_TC_VAR;
586 //lyxerr << "t: " << t << " flags: " << flags << " i: " << ival_
587 // << " '" << sval_ << "'\n";
588 //array.dump(lyxerr);
591 if (flags & FLAG_ITEM) {
593 if (t == LM_TK_OPEN) {
594 // skip the brace and collect everything to the next matching
596 flags |= FLAG_BRACE_LAST;
599 // take only this single token
604 if (flags & FLAG_BRACE) {
605 if (t != LM_TK_OPEN) {
606 error("Expected {. Maybe you forgot to enclose an argument in {}");
610 flags &= ~FLAG_BRACE;
616 if (flags & FLAG_BLOCK) {
617 if (t == LM_TK_CLOSE || t == '&' ||
618 t == LM_TK_NEWLINE || t == LM_TK_END) {
632 if (!isspace(ival_) || yyvarcode == LM_TC_TEXTRM)
633 array.push_back(new MathCharInset(ival_, yyvarcode));
636 case LM_TK_ARGUMENT: {
637 MathMacroArgument * p = new MathMacroArgument(ival_);
638 //p->code(yyvarcode);
644 array.push_back(new MathCharInset(ival_, LM_TC_SPECIAL));
648 array.push_back(new MathCharInset(ival_, LM_TC_CONST));
652 //lyxerr << " creating ScopeInset\n";
653 array.push_back(new MathScopeInset);
654 parse_into(array.back()->cell(0), FLAG_BRACE_LAST);
658 if (flags & FLAG_BRACE_LAST)
663 array.push_back(new MathCharInset('[', LM_TC_CONST));
667 if (flags & FLAG_BRACK_END)
670 array.push_back(new MathCharInset(']', LM_TC_CONST));
675 lastScriptInset(array, true, false, limits)->cell(0), FLAG_ITEM);
680 lastScriptInset(array, false, true, limits)->cell(1), FLAG_ITEM);
685 //lyxerr << "setting limit to " << limits << "\n";
689 if (flags & FLAG_AMPERSAND) {
690 flags &= ~FLAG_AMPERSAND;
693 lyxerr[Debug::MATHED]
694 << "found tab unexpectedly, array: '" << array << "'\n";
699 curr_skip_ = lexArg('[');
700 if (flags & FLAG_NEWLINE) {
701 flags &= ~FLAG_NEWLINE;
704 lyxerr[Debug::MATHED]
705 << "found newline unexpectedly, array: '" << array << "'\n";
713 array.push_back(new MathCharInset(ival_, LM_TC_BOP));
718 unsigned char c = getuchar();
720 array.push_back(new MathRootInset);
721 parse_into(array.back()->cell(0), FLAG_BRACK_END);
722 parse_into(array.back()->cell(1), FLAG_ITEM);
725 array.push_back(new MathSqrtInset);
726 parse_into(array.back()->cell(0), FLAG_ITEM);
733 latexkeys const * l = read_delim();
735 parse_into(ar, FLAG_RIGHT);
736 latexkeys const * r = read_delim();
737 MathDelimInset * dl = new MathDelimInset(l, r);
744 if (flags & FLAG_RIGHT)
746 error("Unmatched right delimiter");
752 MathTextCodes t = static_cast<MathTextCodes>(lval_->id);
754 parse_into(ar, FLAG_ITEM);
755 for (MathArray::iterator it = ar.begin(); it != ar.end(); ++it)
756 (*it)->handleFont(t);
762 yyvarcode = static_cast<MathTextCodes>(lval_->id);
767 lyxerr[Debug::MATHED] << "LM_TK_STY not implemented\n";
768 //MathArray tmp = array;
769 //MathSizeInset * p = new MathSizeInset(MathStyles(lval_->id));
770 //array.push_back(p);
771 //parse_into(p->cell(0), FLAG_BRACE_FONT);
780 if (MathMacroTable::hasTemplate(sval_)) {
781 MathMacro * m = MathMacroTable::cloneTemplate(sval_);
782 for (int i = 0; i < m->nargs(); ++i)
783 parse_into(m->cell(i), FLAG_ITEM);
785 m->metrics(LM_ST_TEXT);
787 array.push_back(new MathFuncInset(sval_));
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 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 curr_label_ = lexArg('{', true);
821 MathInset * p = createMathInset(lval_);
822 p->cell(0).swap(array);
824 parse_into(p->cell(1), FLAG_BLOCK);
830 MathInset * p = createMathInset(lval_);
832 for (int i = 0; i < p->nargs(); ++i)
833 parse_into(p->cell(i), FLAG_ITEM);
836 error("Unrecognized token");
837 //lyxerr[Debug::MATHED] << "[" << t << " " << sval_ << "]\n";
838 lyxerr << "[" << t << " " << sval_ << "]\n";
841 } // end of big switch
843 if (flags & FLAG_LEAVE) {
844 flags &= ~FLAG_LEAVE;
849 lyxerr << " Math Panic, expect problems!\n";
850 // Search for the end command.
853 } while (is_.good() && t != LM_TK_END && t);
861 void parse_end(LyXLex & lex, int lineno)
863 // Update line number
864 lex.setLineNo(lineno);
866 // reading of end_inset
869 if (lex.getString() == "\\end_inset")
871 //lyxerr[Debug::MATHED] << "InsetFormula::Read: Garbage before \\end_inset,"
872 lyxerr << "InsetFormula::Read: Garbage before \\end_inset,"
873 " or missing \\end_inset!\n";
877 } // anonymous namespace
881 MathArray mathed_parse_cell(string const & str)
883 istringstream is(str.c_str());
886 parser.parse_into(ar, 0);
892 MathMacroTemplate * mathed_parse_macro(string const & str)
894 istringstream is(str.c_str());
896 return parser.parse_macro();
899 MathMacroTemplate * mathed_parse_macro(istream & is)
902 return parser.parse_macro();
905 MathMacroTemplate * mathed_parse_macro(LyXLex & lex)
908 MathMacroTemplate * p = parser.parse_macro();
909 parse_end(lex, parser.lineno());
915 MathMatrixInset * mathed_parse_normal(string const & str)
917 istringstream is(str.c_str());
919 return parser.parse_normal();
922 MathMatrixInset * mathed_parse_normal(istream & is)
925 return parser.parse_normal();
928 MathMatrixInset * mathed_parse_normal(LyXLex & lex)
931 MathMatrixInset * p = parser.parse_normal();
932 parse_end(lex, parser.lineno());