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;
568 //lyxerr << "t: " << t << " flags: " << flags << " i: " << ival_
569 // << " '" << sval_ << "'\n";
570 //array.dump(lyxerr);
573 if (flags & FLAG_ITEM) {
575 if (t == LM_TK_OPEN) {
576 // skip the brace and regard everything to the next matching
580 flags |= FLAG_BRACE_LAST;
582 // regard only this single token
587 if ((flags & FLAG_BRACE) && t != LM_TK_OPEN) {
589 "Expected {. Maybe you forgot to enclose an argument in {}");
597 if (!isspace(ival_) || yyvarcode == LM_TC_TEXTRM)
598 array.push_back(new MathCharInset(ival_, yyvarcode));
601 case LM_TK_ARGUMENT: {
602 MathMacroArgument * p = new MathMacroArgument(ival_);
603 //p->code(yyvarcode);
609 array.push_back(new MathCharInset(ival_, LM_TC_SPECIAL));
613 array.push_back(new MathCharInset(ival_, LM_TC_CONST));
617 array.push_back(new MathScopeInset);
618 parse_into(array.back()->cell(0), FLAG_BRACE_LAST);
622 if (flags & FLAG_BRACE_LAST) {
628 array.push_back(new MathCharInset('[', LM_TC_CONST));
632 if (flags & FLAG_BRACK_END)
635 array.push_back(new MathCharInset(']', LM_TC_CONST));
640 lastScriptInset(array, true, false, limits)->cell(0), FLAG_ITEM);
645 lastScriptInset(array, false, true, limits)->cell(1), FLAG_ITEM);
650 //lyxerr << "setting limit to " << limits << "\n";
654 if (flags & FLAG_AMPERSAND) {
655 flags &= ~FLAG_AMPERSAND;
658 lyxerr[Debug::MATHED]
659 << "found tab unexpectedly, array: '" << array << "'\n";
664 curr_skip_ = lexArg('[');
665 if (flags & FLAG_NEWLINE) {
666 flags &= ~FLAG_NEWLINE;
669 lyxerr[Debug::MATHED]
670 << "found newline unexpectedly, array: '" << array << "'\n";
680 array.push_back(new MathNoglyphInset(lval_));
685 array.push_back(new MathBigopInset(lval_));
690 array.push_back(new MathFuncLimInset(lval_));
695 array.push_back(new MathSymbolInset(lval_));
699 array.push_back(new MathCharInset(ival_, LM_TC_BOP));
704 array.push_back(new MathSpaceInset(ival_));
708 array.push_back(new MathDotsInset(lval_));
713 MathStackrelInset * p = new MathStackrelInset;
714 parse_into(p->cell(0), FLAG_ITEM);
715 parse_into(p->cell(1), FLAG_ITEM);
722 MathFracInset * p = new MathFracInset;
723 parse_into(p->cell(0), FLAG_ITEM);
724 parse_into(p->cell(1), FLAG_ITEM);
731 unsigned char c = getuchar();
733 array.push_back(new MathRootInset);
734 parse_into(array.back()->cell(0), FLAG_BRACK_END);
735 parse_into(array.back()->cell(1), FLAG_ITEM);
738 array.push_back(new MathSqrtInset);
739 parse_into(array.back()->cell(0), FLAG_ITEM);
746 latexkeys const * l = read_delim();
748 parse_into(ar, FLAG_RIGHT);
749 latexkeys const * r = read_delim();
750 MathDelimInset * dl = new MathDelimInset(l, r);
757 if (flags & FLAG_RIGHT)
759 error("Unmatched right delimiter");
765 MathTextCodes t = static_cast<MathTextCodes>(lval_->id);
767 parse_into(ar, FLAG_ITEM);
768 for (MathArray::iterator it = ar.begin(); it != ar.end(); ++it)
769 (*it)->handleFont(t);
775 yyvarcode = static_cast<MathTextCodes>(lval_->id);
780 lyxerr[Debug::MATHED] << "LM_TK_STY not implemented\n";
781 //MathArray tmp = array;
782 //MathSizeInset * p = new MathSizeInset(MathStyles(lval_->id));
783 //array.push_back(p);
784 //parse_into(p->cell(0), FLAG_BRACE_FONT);
788 case LM_TK_DECORATION:
790 MathDecorationInset * p = new MathDecorationInset(lval_);
791 parse_into(p->cell(0), FLAG_ITEM);
801 array.push_back(new MathSymbolInset(lval_));
805 if (MathMacroTable::hasTemplate(sval_)) {
806 MathMacro * m = MathMacroTable::cloneTemplate(sval_);
807 for (int i = 0; i < m->nargs(); ++i)
808 parse_into(m->cell(i), FLAG_ITEM);
810 m->metrics(LM_ST_TEXT);
812 array.push_back(new MathFuncInset(sval_));
822 MathInsetTypes typ = latex_mathenv[i].typ;
824 if (typ == LM_OT_MATRIX) {
825 string const valign = lexArg('[') + 'c';
826 string const halign = lexArg('{');
827 //lyxerr << "valign: '" << valign << "'\n";
828 //lyxerr << "halign: '" << halign << "'\n";
829 MathArrayInset * m = new MathArrayInset(halign.size(), 1);
830 m->valign(valign[0]);
833 parse_lines(m, halign.size(), latex_mathenv[i].numbered, false);
835 //lyxerr << "read matrix " << *m << "\n";
838 lyxerr[Debug::MATHED] << "unknow math inset " << typ << "\n";
843 array.push_back(MathMacroTable::cloneTemplate(lval_->name));
847 curr_label_ = lexArg('{', true);
851 error("Unrecognized token");
852 lyxerr[Debug::MATHED] << "[" << t << " " << sval_ << "]" << endl;
855 } // end of big switch
857 if (flags & FLAG_LEAVE) {
858 flags &= ~FLAG_LEAVE;
863 lyxerr << " Math Panic, expect problems!" << endl;
864 // Search for the end command.
867 } while (is_.good() && t != LM_TK_END && t);
875 void parse_end(LyXLex & lex, int lineno)
877 // Update line number
878 lex.setLineNo(lineno);
880 // reading of end_inset
883 if (lex.getString() == "\\end_inset")
885 lyxerr[Debug::MATHED] << "InsetFormula::Read: Garbage before \\end_inset,"
886 " or missing \\end_inset!" << endl;
890 } // anonymous namespace
894 MathArray mathed_parse_cell(string const & str)
896 istringstream is(str.c_str());
899 parser.parse_into(ar, 0);
905 MathMacroTemplate * mathed_parse_macro(string const & str)
907 istringstream is(str.c_str());
909 return parser.parse_macro();
912 MathMacroTemplate * mathed_parse_macro(istream & is)
915 return parser.parse_macro();
918 MathMacroTemplate * mathed_parse_macro(LyXLex & lex)
921 MathMacroTemplate * p = parser.parse_macro();
922 parse_end(lex, parser.lineno());
928 MathMatrixInset * mathed_parse_normal(string const & str)
930 istringstream is(str.c_str());
932 return parser.parse_normal();
935 MathMatrixInset * mathed_parse_normal(istream & is)
938 return parser.parse_normal();
941 MathMatrixInset * mathed_parse_normal(LyXLex & lex)
944 MathMatrixInset * p = parser.parse_normal();
945 parse_end(lex, parser.lineno());