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_scopeinset.h"
45 #include "math_sqrtinset.h"
46 #include "math_scriptinset.h"
47 #include "math_sizeinset.h"
48 #include "math_spaceinset.h"
49 #include "math_sqrtinset.h"
50 #include "math_stackrelinset.h"
51 #include "math_symbolinset.h"
53 #include "mathed/support.h"
55 #include "support/lstrings.h"
63 MathScriptInset * prevScriptInset(MathArray const & array)
65 MathInset * p = array.back();
66 return (p && p->isScriptInset()) ? static_cast<MathScriptInset *>(p) : 0;
70 MathInset * lastScriptInset(MathArray & array, bool up, bool down, int limits)
72 MathScriptInset * p = prevScriptInset(array);
74 MathInset * b = array.back();
75 if (b && b->isScriptable()) {
76 p = new MathScriptInset(up, down, b->clone());
79 p = new MathScriptInset(up, down);
93 // These are lexical codes, not semantic
98 LexBOP, // Binary operators or relations
110 lexcode_enum lexcode[256];
113 const unsigned char LM_TK_OPEN = '{';
114 const unsigned char LM_TK_CLOSE = '}';
117 FLAG_BRACE = 1 << 0, // A { needed //}
118 FLAG_BRACE_LAST = 1 << 1, // // { Last } ends the parsing process
119 FLAG_RIGHT = 1 << 2, // Next right ends the parsing process
120 FLAG_END = 1 << 3, // Next end ends the parsing process
121 FLAG_BRACK_END = 1 << 5, // // [ Next ] ends the parsing process
122 FLAG_AMPERSAND = 1 << 6, // Next & ends the parsing process
123 FLAG_NEWLINE = 1 << 7, // Next \\ ends the parsing process
124 FLAG_ITEM = 1 << 8, // read a (possibly braced token)
125 FLAG_LEAVE = 1 << 9, // marker for leaving the
126 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]);
159 for (int i = 0; i <= 255; ++i) {
161 lexcode[i] = LexOther;
163 lexcode[i] = LexSpace;
165 lexcode[i] = LexAlpha;
168 lexcode['\t'] = lexcode['\f'] = lexcode[' '] = LexSpace;
169 lexcode['\n'] = LexNewLine;
170 lexcode['%'] = LexComment;
171 lexcode['#'] = LexArgument;
172 lexcode['$'] = LexMath;
173 lexcode['+'] = lexcode['-'] = lexcode['*'] = lexcode['/']
174 = lexcode['<'] = lexcode['>'] = lexcode['='] = LexBOP;
176 lexcode['('] = lexcode[')'] = lexcode['|'] = lexcode['.'] =
177 lexcode['?'] = LexOther;
179 lexcode['\''] = lexcode['@'] = LexAlpha;
181 lexcode['['] = lexcode[']'] = lexcode['^'] = lexcode['_'] =
182 lexcode['&'] = LexSelf;
184 lexcode['\\'] = LexESC;
185 lexcode['{'] = LexOpen;
186 lexcode['}'] = LexClose;
192 // Helper class for parsing
199 Parser(LyXLex & lex) : is_(lex.getStream()), lineno_(lex.getLineNo()) {}
201 Parser(istream & is) : is_(is), lineno_(0) {}
204 MathMacroTemplate * parse_macro();
206 MathMatrixInset * parse_normal();
208 void parse_into(MathArray & array, unsigned flags);
210 int lineno() const { return lineno_; }
216 string lexArg(unsigned char lf, bool accept_spaces = false);
218 unsigned char getuchar();
220 void error(string const & msg);
222 void parse_lines(MathGridInset * p, int col, bool numbered, bool outmost);
224 latexkeys const * read_delim();
235 latexkeys const * lval_;
248 unsigned char Parser::getuchar()
252 lyxerr << "The input stream is not well..." << endl;
254 return static_cast<unsigned char>(c);
258 string Parser::lexArg(unsigned char lf, bool accept_spaces = false)
273 unsigned char rg = 0;
274 if (lf == '{') rg = '}';
275 if (lf == '[') rg = ']';
276 if (lf == '(') rg = ')';
278 lyxerr[Debug::MATHED] << "Math parse error: unknown bracket '"
279 << lf << "'" << endl;
285 unsigned char c = getuchar();
290 if ((!isspace(c) || (c == ' ' && accept_spaces)) && depth > 0)
292 } while (depth > 0 && is_.good());
300 static bool init_done = false;
308 unsigned char c = getuchar();
309 //lyxerr << "reading byte: '" << c << "' code: " << lexcode[c] << endl;
311 if (lexcode[c] == LexNewLine) {
314 } else if (lexcode[c] == LexComment) {
317 } while (c != '\n' && is_.good()); // eat comments
318 } else if (lexcode[c] == LexOther) {
321 } else if (lexcode[c] == LexAlpha || lexcode[c] == LexSpace) {
324 } else if (lexcode[c] == LexBOP) {
327 } else if (lexcode[c] == LexMath) {
330 } else if (lexcode[c] == LexSelf) {
332 } else if (lexcode[c] == LexArgument) {
335 return LM_TK_ARGUMENT;
336 } else if (lexcode[c] == LexOpen) {
338 } else if (lexcode[c] == LexClose) {
340 } else if (lexcode[c] == LexESC) {
342 //lyxerr << "reading second byte: '" << c << "' code: " << lexcode[c] << endl;
345 latexkeys const * l = in_word_set(s);
347 //lyxerr << "found key: " << l << endl;
348 //lyxerr << "found key name: " << l->name << endl;
349 //lyxerr << "found key token: " << l->token << endl;
354 if (lexcode[c] == LexAlpha) {
356 while (lexcode[c] == LexAlpha && is_.good()) {
360 while (lexcode[c] == LexSpace && is_.good())
362 if (lexcode[c] != LexSpace)
365 //lyxerr[Debug::MATHED] << "reading: text '" << sval_ << "'\n";
366 //lyxerr << "reading: text '" << sval_ << "'\n";
367 latexkeys const * l = in_word_set(sval_);
371 if (l->token == LM_TK_BEGIN || l->token == LM_TK_END) {
372 string name = lexArg('{');
374 while (i < latex_mathenv_num && name != latex_mathenv[i].name)
377 } else if (l->token == LM_TK_SPACE)
389 void Parser::error(string const & msg)
391 lyxerr << "Line ~" << lineno_ << ": Math parse error: " << msg << endl;
395 void Parser::parse_lines(MathGridInset * p, int col, bool numbered, bool outmost)
397 // save global variables
398 bool const saved_num = curr_num_;
399 string const saved_label = curr_label_;
401 for (int row = 0; true; ++row) {
402 // reset global variables
403 curr_num_ = numbered;
407 int idx = p->nargs() - p->ncols();
408 for (int i = 0; i < col - 1; ++i, ++idx)
409 parse_into(p->cell(idx), FLAG_AMPERSAND);
410 parse_into(p->cell(idx), FLAG_NEWLINE | FLAG_END);
413 MathMatrixInset * m = static_cast<MathMatrixInset *>(p);
414 m->numbered(row, curr_num_);
415 m->label(row, curr_label_);
416 if (curr_skip_.size()) {
417 m->vskip(LyXLength(curr_skip_), row);
432 // restore "global" variables
433 curr_num_ = saved_num;
434 curr_label_ = saved_label;
438 MathMacroTemplate * Parser::parse_macro()
440 if (yylex() != LM_TK_NEWCOMMAND) {
441 lyxerr << "\\newcommand expected\n";
445 string name = lexArg('{').substr(1);
446 string arg = lexArg('[');
447 int narg = arg.empty() ? 0 : atoi(arg.c_str());
448 MathMacroTemplate * p = new MathMacroTemplate(name, narg);
449 parse_into(p->cell(0), FLAG_BRACE | FLAG_BRACE_LAST);
454 MathMatrixInset * Parser::parse_normal()
456 MathMatrixInset * p = 0;
463 lyxerr[Debug::MATHED]
464 << "reading math environment " << i << " "
465 << latex_mathenv[i].name << "\n";
467 MathInsetTypes typ = latex_mathenv[i].typ;
468 p = new MathMatrixInset(typ);
473 curr_num_ = latex_mathenv[i].numbered;
475 parse_into(p->cell(0), 0);
476 p->numbered(0, curr_num_);
477 p->label(0, curr_label_);
481 case LM_OT_EQUATION: {
482 curr_num_ = latex_mathenv[i].numbered;
484 parse_into(p->cell(0), FLAG_END);
485 p->numbered(0, curr_num_);
486 p->label(0, curr_label_);
490 case LM_OT_EQNARRAY: {
491 parse_lines(p, 3, latex_mathenv[i].numbered, true);
496 p->halign(lexArg('{'));
497 parse_lines(p, 2, latex_mathenv[i].numbered, true);
501 case LM_OT_ALIGNAT: {
502 p->halign(lexArg('{'));
503 parse_lines(p, 2, latex_mathenv[i].numbered, true);
508 lyxerr[Debug::MATHED]
509 << "1: unknown math environment: " << typ << "\n";
516 lyxerr[Debug::MATHED]
517 << "2 unknown math environment: " << t << "\n";
524 latexkeys const * Parser::read_delim()
527 //lyxerr << "found symbol: " << ld << "\n";
528 latexkeys const * l = in_word_set(".");
535 //lyxerr << "found key 1: '" << l << "'\n";
536 //lyxerr << "found key 1: '" << l->name << "'\n";
544 //lyxerr << "found key 2: '" << l->name << "'\n";
551 //lyxerr << "found key 2: '" << l->name << "'\n";
558 void Parser::parse_into(MathArray & array, unsigned flags)
560 MathTextCodes yyvarcode = LM_TC_VAR;
567 //lyxerr << "t: " << t << " flags: " << flags << " i: " << ival_
568 // << " '" << sval_ << "'\n";
569 //array.dump(lyxerr);
572 if (flags & FLAG_ITEM) {
574 if (t == LM_TK_OPEN) {
575 // skip the brace and collect everything to the next matching
578 flags |= FLAG_BRACE_LAST;
580 // take only this single token
585 if ((flags & FLAG_BRACE) && t != LM_TK_OPEN) {
586 error("Expected {. Maybe you forgot to enclose an argument in {}");
594 if (!isspace(ival_) || yyvarcode == LM_TC_TEXTRM)
595 array.push_back(new MathCharInset(ival_, yyvarcode));
598 case LM_TK_ARGUMENT: {
599 MathMacroArgument * p = new MathMacroArgument(ival_);
600 //p->code(yyvarcode);
606 array.push_back(new MathCharInset(ival_, LM_TC_SPECIAL));
610 array.push_back(new MathCharInset(ival_, LM_TC_CONST));
614 array.push_back(new MathScopeInset);
615 parse_into(array.back()->cell(0), FLAG_BRACE_LAST);
619 if (flags & FLAG_BRACE_LAST) {
625 array.push_back(new MathCharInset('[', LM_TC_CONST));
629 if (flags & FLAG_BRACK_END)
632 array.push_back(new MathCharInset(']', LM_TC_CONST));
637 lastScriptInset(array, true, false, limits)->cell(0), FLAG_ITEM);
642 lastScriptInset(array, false, true, limits)->cell(1), FLAG_ITEM);
647 //lyxerr << "setting limit to " << limits << "\n";
651 if (flags & FLAG_AMPERSAND) {
652 flags &= ~FLAG_AMPERSAND;
655 lyxerr[Debug::MATHED]
656 << "found tab unexpectedly, array: '" << array << "'\n";
661 curr_skip_ = lexArg('[');
662 if (flags & FLAG_NEWLINE) {
663 flags &= ~FLAG_NEWLINE;
666 lyxerr[Debug::MATHED]
667 << "found newline unexpectedly, array: '" << array << "'\n";
677 array.push_back(new MathNoglyphInset(lval_));
682 array.push_back(new MathBigopInset(lval_));
687 array.push_back(new MathFuncLimInset(lval_));
692 array.push_back(new MathSymbolInset(lval_));
696 array.push_back(new MathCharInset(ival_, LM_TC_BOP));
701 array.push_back(new MathSpaceInset(ival_));
705 array.push_back(new MathDotsInset(lval_));
710 MathStackrelInset * p = new MathStackrelInset;
711 parse_into(p->cell(0), FLAG_ITEM);
712 parse_into(p->cell(1), FLAG_ITEM);
719 MathFracInset * p = new MathFracInset;
720 parse_into(p->cell(0), FLAG_ITEM);
721 parse_into(p->cell(1), FLAG_ITEM);
728 unsigned char c = getuchar();
730 array.push_back(new MathRootInset);
731 parse_into(array.back()->cell(0), FLAG_BRACK_END);
732 parse_into(array.back()->cell(1), FLAG_ITEM);
735 array.push_back(new MathSqrtInset);
736 parse_into(array.back()->cell(0), FLAG_ITEM);
743 latexkeys const * l = read_delim();
745 parse_into(ar, FLAG_RIGHT);
746 latexkeys const * r = read_delim();
747 MathDelimInset * dl = new MathDelimInset(l, r);
754 if (flags & FLAG_RIGHT)
756 error("Unmatched right delimiter");
762 MathTextCodes t = static_cast<MathTextCodes>(lval_->id);
764 parse_into(ar, FLAG_ITEM);
765 for (MathArray::iterator it = ar.begin(); it != ar.end(); ++it)
766 (*it)->handleFont(t);
772 yyvarcode = static_cast<MathTextCodes>(lval_->id);
777 lyxerr[Debug::MATHED] << "LM_TK_STY not implemented\n";
778 //MathArray tmp = array;
779 //MathSizeInset * p = new MathSizeInset(MathStyles(lval_->id));
780 //array.push_back(p);
781 //parse_into(p->cell(0), FLAG_BRACE_FONT);
785 case LM_TK_DECORATION:
787 MathDecorationInset * p = new MathDecorationInset(lval_);
788 parse_into(p->cell(0), FLAG_ITEM);
798 array.push_back(new MathSymbolInset(lval_));
802 if (MathMacroTable::hasTemplate(sval_)) {
803 MathMacro * m = MathMacroTable::cloneTemplate(sval_);
804 for (int i = 0; i < m->nargs(); ++i)
805 parse_into(m->cell(i), FLAG_ITEM);
807 m->metrics(LM_ST_TEXT);
809 array.push_back(new MathFuncInset(sval_));
819 MathInsetTypes typ = latex_mathenv[i].typ;
821 if (typ == LM_OT_MATRIX) {
822 string const valign = lexArg('[') + 'c';
823 string const halign = lexArg('{');
824 //lyxerr << "valign: '" << valign << "'\n";
825 //lyxerr << "halign: '" << halign << "'\n";
826 MathArrayInset * m = new MathArrayInset(halign.size(), 1);
827 m->valign(valign[0]);
830 parse_lines(m, halign.size(), latex_mathenv[i].numbered, false);
832 //lyxerr << "read matrix " << *m << "\n";
835 lyxerr[Debug::MATHED] << "unknow math inset " << typ << "\n";
840 array.push_back(MathMacroTable::cloneTemplate(lval_->name));
844 curr_label_ = lexArg('{', true);
848 error("Unrecognized token");
849 lyxerr[Debug::MATHED] << "[" << t << " " << sval_ << "]" << endl;
852 } // end of big switch
854 if (flags & FLAG_LEAVE) {
855 flags &= ~FLAG_LEAVE;
860 lyxerr << " Math Panic, expect problems!" << endl;
861 // Search for the end command.
864 } while (is_.good() && t != LM_TK_END && t);
872 void parse_end(LyXLex & lex, int lineno)
874 // Update line number
875 lex.setLineNo(lineno);
877 // reading of end_inset
880 if (lex.getString() == "\\end_inset")
882 lyxerr[Debug::MATHED] << "InsetFormula::Read: Garbage before \\end_inset,"
883 " or missing \\end_inset!" << endl;
887 } // anonymous namespace
891 MathArray mathed_parse_cell(string const & str)
893 istringstream is(str.c_str());
896 parser.parse_into(ar, 0);
902 MathMacroTemplate * mathed_parse_macro(string const & str)
904 istringstream is(str.c_str());
906 return parser.parse_macro();
909 MathMacroTemplate * mathed_parse_macro(istream & is)
912 return parser.parse_macro();
915 MathMacroTemplate * mathed_parse_macro(LyXLex & lex)
918 MathMacroTemplate * p = parser.parse_macro();
919 parse_end(lex, parser.lineno());
925 MathMatrixInset * mathed_parse_normal(string const & str)
927 istringstream is(str.c_str());
929 return parser.parse_normal();
932 MathMatrixInset * mathed_parse_normal(istream & is)
935 return parser.parse_normal();
938 MathMatrixInset * mathed_parse_normal(LyXLex & lex)
941 MathMatrixInset * p = parser.parse_normal();
942 parse_end(lex, parser.lineno());