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"
56 bool stared(string const & s)
58 unsigned n = s.size();
59 return n && s[n - 1] == '*';
62 MathScriptInset * prevScriptInset(MathArray const & array)
64 MathInset * p = array.back();
65 return (p && p->isScriptInset()) ? static_cast<MathScriptInset *>(p) : 0;
69 MathInset * lastScriptInset(MathArray & array, bool up, int limits)
71 MathScriptInset * p = prevScriptInset(array);
73 MathInset * b = array.back();
74 if (b && b->isScriptable()) {
75 p = new MathScriptInset(up, !up, b->clone());
78 p = new MathScriptInset(up, !up);
92 // These are TeX's catcodes
94 catEscape, // 0 backslash
104 catSpace, // 10 space
105 catLetter, // 11 a-zA-Z
106 catOther, // 12 none of the above
109 catInvalid // 15 <delete>
112 CatCode theCatcode[256];
115 inline CatCode catcode(unsigned char c)
117 return theCatcode[c];
122 FLAG_BRACE = 1 << 0, // an opening brace needed
123 FLAG_BRACE_LAST = 1 << 1, // last closing brace ends the parsing process
124 FLAG_RIGHT = 1 << 2, // next \\right ends the parsing process
125 FLAG_END = 1 << 3, // next \\end ends the parsing process
126 FLAG_BRACK_END = 1 << 4, // next closing bracket ends the parsing process
127 FLAG_NEWLINE = 1 << 6, // next \\\\ ends the parsing process
128 FLAG_ITEM = 1 << 7, // read a (possibly braced token)
129 FLAG_BLOCK = 1 << 8, // next block ends the parsing process
130 FLAG_LEAVE = 1 << 9 // leave the loop at the end
136 for (int i = 0; i <= 255; ++i)
137 theCatcode[i] = catOther;
138 for (int i = 'a'; i <= 'z'; ++i)
139 theCatcode[i] = catLetter;
140 for (int i = 'A'; i <= 'Z'; ++i)
141 theCatcode[i] = catLetter;
143 theCatcode['\\'] = catEscape;
144 theCatcode['{'] = catBegin;
145 theCatcode['}'] = catEnd;
146 theCatcode['$'] = catMath;
147 theCatcode['&'] = catAlign;
148 theCatcode['\n'] = catNewline;
149 theCatcode['#'] = catParameter;
150 theCatcode['^'] = catSuper;
151 theCatcode['_'] = catSub;
152 theCatcode['
\7f'] = catIgnore;
153 theCatcode[' '] = catSpace;
154 theCatcode['\t'] = catSpace;
155 theCatcode['\r'] = catSpace;
156 theCatcode['~'] = catActive;
157 theCatcode['%'] = catComment;
163 // Helper class for parsing
169 Token() : cs_(), char_(0), cat_(catIgnore) {}
171 Token(char c, CatCode cat) : cs_(), char_(c), cat_(cat) {}
173 Token(const string & cs) : cs_(cs), char_(0), cat_(catIgnore) {}
176 string const & cs() const { return cs_; }
178 CatCode cat() const { return cat_; }
180 char character() const { return char_; }
182 string asString() const;
193 string Token::asString() const
195 return cs_.size() ? cs_ : string(1, char_);
198 bool operator==(Token const & s, Token const & t)
200 return s.character() == t.character()
201 && s.cat() == t.cat() && s.cs() == t.cs();
204 bool operator!=(Token const & s, Token const & t)
209 ostream & operator<<(ostream & os, Token const & t)
212 os << "\\" << t.cs();
214 os << "[" << t.character() << "," << t.cat() << "]";
223 Parser(LyXLex & lex);
225 Parser(istream & is);
228 MathMacroTemplate * parse_macro();
230 MathMatrixInset * parse_normal();
232 void parse_into(MathArray & array, unsigned flags);
234 int lineno() const { return lineno_; }
240 string getArg(char lf, char rf);
244 void error(string const & msg);
246 void parse_lines(MathGridInset * p, bool numbered, bool outmost);
248 latexkeys const * read_delim();
252 void tokenize(istream & is);
254 void tokenize(string const & s);
256 void push_back(Token const & t);
260 Token const & prevToken() const;
262 Token const & nextToken() const;
264 Token const & getToken();
266 void lex(string const & s);
273 std::vector<Token> tokens_;
285 Parser::Parser(LyXLex & lexer)
286 : lineno_(lexer.getLineNo()), pos_(0), curr_num_(false)
288 tokenize(lexer.getStream());
292 Parser::Parser(istream & is)
293 : lineno_(0), pos_(0), curr_num_(false)
299 void Parser::push_back(Token const & t)
301 tokens_.push_back(t);
305 void Parser::pop_back()
311 Token const & Parser::prevToken() const
313 static const Token dummy;
314 return pos_ > 0 ? tokens_[pos_ - 1] : dummy;
318 Token const & Parser::nextToken() const
320 static const Token dummy;
321 return good() ? tokens_[pos_] : dummy;
325 Token const & Parser::getToken()
327 static const Token dummy;
328 return good() ? tokens_[pos_++] : dummy;
332 void Parser::putback()
338 bool Parser::good() const
340 return pos_ < tokens_.size();
344 char Parser::getChar()
347 lyxerr << "The input stream is not well..." << endl;
348 return tokens_[pos_++].character();
352 string Parser::getArg(char lf, char rg)
360 while ((c = getChar()) != rg && good())
367 void Parser::tokenize(istream & is)
369 // eat everything up to the next \end_inset or end of stream
370 // and store it in s for further tokenization
375 if (s.size() >= 10 && s.substr(s.size() - 10) == "\\end_inset") {
376 s = s.substr(0, s.size() - 10);
386 void Parser::tokenize(string const & buffer)
388 static bool init_done = false;
395 istringstream is(buffer, ios::in | ios::binary);
400 switch (catcode(c)) {
404 if (catcode(c) == catNewline)
405 ; //push_back(Token("par"));
407 push_back(Token(' ', catSpace));
414 while (is.get(c) && catcode(c) != catNewline)
423 if (catcode(c) == catLetter) {
424 while (is.get(c) && catcode(c) == catLetter)
426 if (catcode(c) == catSpace)
427 while (is.get(c) && catcode(c) == catSpace)
436 push_back(Token(c, catcode(c)));
441 lyxerr << "\nTokens: ";
442 for (unsigned i = 0; i < tokens_.size(); ++i)
443 lyxerr << tokens_[i];
449 void Parser::error(string const & msg)
451 lyxerr << "Line ~" << lineno_ << ": Math parse error: " << msg << endl;
455 void Parser::parse_lines(MathGridInset * p, bool numbered, bool outmost)
457 const int cols = p->ncols();
459 // save global variables
460 bool const saved_num = curr_num_;
461 string const saved_label = curr_label_;
463 for (int row = 0; true; ++row) {
464 // reset global variables
465 curr_num_ = numbered;
469 for (int col = 0; col < cols; ++col) {
470 //lyxerr << "reading cell " << row << " " << col << "\n";
471 parse_into(p->cell(col + row * cols), FLAG_BLOCK);
474 if (prevToken().cat() != catAlign) {
475 //lyxerr << "less cells read than normal in row/col: "
476 // << row << " " << col << "\n";
482 MathMatrixInset * m = static_cast<MathMatrixInset *>(p);
483 m->numbered(row, curr_num_);
484 m->label(row, curr_label_);
485 if (curr_skip_.size()) {
486 m->vskip(LyXLength(curr_skip_), row);
492 if (prevToken() != Token("\\")) {
493 //lyxerr << "no newline here\n";
500 // restore "global" variables
501 curr_num_ = saved_num;
502 curr_label_ = saved_label;
506 MathMacroTemplate * Parser::parse_macro()
508 while (nextToken().cat() == catSpace)
511 if (getToken().cs() != "newcommand") {
512 lyxerr << "\\newcommand expected\n";
516 if (getToken().cat() != catBegin) {
517 lyxerr << "'{' expected\n";
521 string name = getToken().cs();
523 if (getToken().cat() != catEnd) {
524 lyxerr << "'}' expected\n";
528 string arg = getArg('[', ']');
529 int narg = arg.empty() ? 0 : atoi(arg.c_str());
530 //lyxerr << "creating macro " << name << " with " << narg << "args\n";
531 MathMacroTemplate * p = new MathMacroTemplate(name, narg);
532 parse_into(p->cell(0), FLAG_BRACE | FLAG_BRACE_LAST);
537 MathMatrixInset * Parser::parse_normal()
539 Token const & t = getToken();
541 if (t.cat() == catMath || t.cs() == "(") {
542 MathMatrixInset * p = new MathMatrixInset(LM_OT_SIMPLE);
543 parse_into(p->cell(0), 0);
547 if (!t.cs().size()) {
548 lyxerr << "start of math expected, got '" << t << "'\n";
552 string const & cs = t.cs();
557 MathMatrixInset * p = new MathMatrixInset(LM_OT_EQUATION);
558 parse_into(p->cell(0), 0);
559 p->numbered(0, curr_num_);
560 p->label(0, curr_label_);
565 lyxerr << "'begin' of un-simple math expected, got '" << cs << "'\n";
569 string const name = getArg('{', '}');
571 if (name == "equation" || name == "equation*") {
572 curr_num_ = !stared(name);
574 MathMatrixInset * p = new MathMatrixInset(LM_OT_EQUATION);
575 parse_into(p->cell(0), FLAG_END);
576 p->numbered(0, curr_num_);
577 p->label(0, curr_label_);
581 if (name == "eqnarray" || name == "eqnarray*") {
582 MathMatrixInset * p = new MathMatrixInset(LM_OT_EQNARRAY);
583 parse_lines(p, !stared(name), true);
587 if (name == "align" || name == "align*") {
588 MathMatrixInset * p = new MathMatrixInset(LM_OT_ALIGN);
589 p->halign(getArg('{', '}'));
590 parse_lines(p, !stared(name), true);
594 if (name == "alignat" || name == "alignat*") {
595 MathMatrixInset * p = new MathMatrixInset(LM_OT_ALIGNAT);
596 p->halign(getArg('{', '}'));
597 parse_lines(p, !stared(name), true);
601 lyxerr[Debug::MATHED] << "1: unknown math environment: " << name << "\n";
606 latexkeys const * Parser::read_delim()
608 Token const & t = getToken();
609 latexkeys const * l = in_word_set(t.asString());
610 return l ? l : in_word_set(".");
614 void Parser::parse_into(MathArray & array, unsigned flags)
616 MathTextCodes yyvarcode = LM_TC_MIN;
622 Token const & t = getToken();
624 //lyxerr << "t: " << t << " flags: " << flags << "'\n";
625 //array.dump(lyxerr);
628 if (flags & FLAG_ITEM) {
630 if (t.cat() == catBegin) {
631 // skip the brace and collect everything to the next matching
633 flags |= FLAG_BRACE_LAST;
636 // handle only this single token, leave the loop if done
641 if (flags & FLAG_BRACE) {
642 if (t.cat() != catBegin) {
643 error("Expected {. Maybe you forgot to enclose an argument in {}");
647 flags &= ~FLAG_BRACE;
652 if (flags & FLAG_BLOCK) {
653 if (t.cat() == catEnd || t.cat() == catAlign || t.cs() == "\\")
655 if (t.cs() == "end") {
664 if (t.cat() == catMath)
667 else if (t.cat() == catLetter)
668 array.push_back(new MathCharInset(t.character(), yyvarcode));
670 else if (t.cat() == catSpace && yyvarcode == LM_TC_TEXTRM)
671 array.push_back(new MathCharInset(' ', yyvarcode));
673 else if (t.cat() == catParameter) {
674 Token const & n = getToken();
675 MathMacroArgument * p = new MathMacroArgument(n.character() - '0');
679 else if (t.cat() == catBegin) {
680 //lyxerr << " creating ScopeInset\n";
681 array.push_back(new MathScopeInset);
682 parse_into(array.back()->cell(0), FLAG_BRACE_LAST);
685 else if (t.cat() == catEnd) {
686 if (!(flags & FLAG_BRACE_LAST))
687 lyxerr << " ##### unexpected end of block\n";
691 else if (t.cat() == catAlign) {
692 lyxerr << "found tab unexpectedly, array: '" << array << "'\n";
696 else if (t.cat() == catSuper)
697 parse_into(lastScriptInset(array, true, limits)->cell(0), FLAG_ITEM);
699 else if (t.cat() == catSub)
700 parse_into(lastScriptInset(array, false, limits)->cell(1), FLAG_ITEM);
702 else if (t.character() == ']' && (flags & FLAG_BRACK_END))
705 else if (t.cat() == catOther)
706 array.push_back(new MathCharInset(t.character(), yyvarcode));
711 else if (t.cs() == "protect")
714 else if (t.cs() == "end")
717 else if (t.cs() == ")")
720 else if (t.cs() == "]")
723 else if (t.cs() == "\\") {
724 curr_skip_ = getArg('[', ']');
725 if (!(flags & FLAG_NEWLINE))
726 lyxerr[Debug::MATHED]
727 << "found newline unexpectedly, array: '" << array << "'\n";
731 else if (t.cs() == "limits")
734 else if (t.cs() == "nolimits")
737 else if (t.cs() == "nonumber")
740 else if (t.cs() == "number")
743 else if (t.cs() == "sqrt") {
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);
756 else if (t.cs() == "left") {
757 latexkeys const * l = read_delim();
759 parse_into(ar, FLAG_RIGHT);
760 latexkeys const * r = read_delim();
761 MathDelimInset * dl = new MathDelimInset(l, r);
766 else if (t.cs() == "right") {
767 if (!(flags & FLAG_RIGHT))
768 error("Unmatched right delimiter");
775 lyxerr[Debug::MATHED] << "LM_TK_STY not implemented\n";
776 //MathArray tmp = array;
777 //MathSizeInset * p = new MathSizeInset(MathStyles(lval_->id));
778 //array.push_back(p);
779 //parse_into(p->cell(0), FLAG_BRACE_FONT);
784 if (MathMacroTable::hasTemplate(sval_)) {
785 MathMacro * m = MathMacroTable::cloneTemplate(sval_);
786 for (int i = 0; i < m->nargs(); ++i)
787 parse_into(m->cell(i), FLAG_ITEM);
789 m->metrics(LM_ST_TEXT);
791 array.push_back(new MathFuncInset(sval_));
795 array.push_back(new MathCharInset(ival_, LM_TC_SPECIAL));
799 else if (t.cs() == "begin") {
800 string const name = getArg('{', '}');
801 if (name == "array") {
802 string const valign = getArg('[', ']') + 'c';
803 string const halign = getArg('{', '}');
804 MathArrayInset * m = new MathArrayInset(halign.size(), 1);
805 m->valign(valign[0]);
807 parse_lines(m, false, false);
810 lyxerr[Debug::MATHED] << "unknow math inset begin '" << name << "'\n";
813 else if (t.cs() == "label") {
815 parse_into(ar, FLAG_ITEM);
818 curr_label_ = os.str();
820 //curr_label_ = getArg('{', '}');
823 else if (t.cs() == "choose" || t.cs() == "over") {
825 MathInset * p = createMathInset(t.cs());
826 p->cell(0).swap(array);
828 parse_into(p->cell(1), FLAG_BLOCK);
831 else if (t.cs().size()) {
833 latexkeys const * l = in_word_set(t.cs());
835 if (l->token == LM_TK_FONT) {
836 //lyxerr << "starting font\n";
838 parse_into(ar, FLAG_ITEM);
839 for (MathArray::iterator it = ar.begin(); it != ar.end(); ++it)
840 (*it)->handleFont(static_cast<MathTextCodes>(l->id));
842 //lyxerr << "ending font\n";
845 else if (l->token == LM_TK_OLDFONT)
846 yyvarcode = static_cast<MathTextCodes>(l->id);
849 MathInset * p = createMathInset(t.cs());
850 for (int i = 0; i < p->nargs(); ++i)
851 parse_into(p->cell(i), FLAG_ITEM);
857 MathInset * p = createMathInset(t.cs());
859 for (int i = 0; i < p->nargs(); ++i)
860 parse_into(p->cell(i), FLAG_ITEM);
863 error("Unrecognized token");
864 //lyxerr[Debug::MATHED] << "[" << t << "]\n";
871 if (flags & FLAG_LEAVE) {
872 flags &= ~FLAG_LEAVE;
878 lyxerr << " Math Panic, expect problems!\n";
879 // Search for the end command.
883 } while (good() && t.cs() != "end");
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 return parser.parse_macro();
923 MathMatrixInset * mathed_parse_normal(string const & str)
925 istringstream is(str.c_str());
927 return parser.parse_normal();
930 MathMatrixInset * mathed_parse_normal(istream & is)
933 return parser.parse_normal();
936 MathMatrixInset * mathed_parse_normal(LyXLex & lex)
939 return parser.parse_normal();