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_kerninset.h"
35 #include "math_macro.h"
36 #include "math_macrotable.h"
37 #include "math_macrotemplate.h"
38 #include "math_matrixinset.h"
39 #include "math_rootinset.h"
40 #include "math_sqrtinset.h"
41 #include "math_scriptinset.h"
42 #include "math_specialcharinset.h"
43 #include "math_splitinset.h"
44 #include "math_sqrtinset.h"
48 #include "support/lstrings.h"
58 bool stared(string const & s)
60 unsigned n = s.size();
61 return n && s[n - 1] == '*';
65 void add(MathArray & ar, char c, MathTextCodes code)
67 ar.push_back(MathAtom(new MathCharInset(c, code)));
71 // These are TeX's catcodes
73 catEscape, // 0 backslash
84 catLetter, // 11 a-zA-Z
85 catOther, // 12 none of the above
88 catInvalid // 15 <delete>
91 CatCode theCatcode[256];
94 inline CatCode catcode(unsigned char c)
101 FLAG_BRACE = 1 << 0, // an opening brace needed
102 FLAG_BRACE_LAST = 1 << 1, // last closing brace ends the parsing process
103 FLAG_RIGHT = 1 << 2, // next \\right ends the parsing process
104 FLAG_END = 1 << 3, // next \\end ends the parsing process
105 FLAG_BRACK_END = 1 << 4, // next closing bracket ends the parsing process
106 FLAG_NEWLINE = 1 << 6, // next \\\\ ends the parsing process
107 FLAG_ITEM = 1 << 7, // read a (possibly braced token)
108 FLAG_BLOCK = 1 << 8, // next block ends the parsing process
109 FLAG_LEAVE = 1 << 9 // leave the loop at the end
115 for (int i = 0; i <= 255; ++i)
116 theCatcode[i] = catOther;
117 for (int i = 'a'; i <= 'z'; ++i)
118 theCatcode[i] = catLetter;
119 for (int i = 'A'; i <= 'Z'; ++i)
120 theCatcode[i] = catLetter;
122 theCatcode['\\'] = catEscape;
123 theCatcode['{'] = catBegin;
124 theCatcode['}'] = catEnd;
125 theCatcode['$'] = catMath;
126 theCatcode['&'] = catAlign;
127 theCatcode['\n'] = catNewline;
128 theCatcode['#'] = catParameter;
129 theCatcode['^'] = catSuper;
130 theCatcode['_'] = catSub;
131 theCatcode['
\7f'] = catIgnore;
132 theCatcode[' '] = catSpace;
133 theCatcode['\t'] = catSpace;
134 theCatcode['\r'] = catSpace;
135 theCatcode['~'] = catActive;
136 theCatcode['%'] = catComment;
142 // Helper class for parsing
148 Token() : cs_(), char_(0), cat_(catIgnore) {}
150 Token(char c, CatCode cat) : cs_(), char_(c), cat_(cat) {}
152 Token(const string & cs) : cs_(cs), char_(0), cat_(catIgnore) {}
155 string const & cs() const { return cs_; }
157 CatCode cat() const { return cat_; }
159 char character() const { return char_; }
161 string asString() const;
172 string Token::asString() const
174 return cs_.size() ? cs_ : string(1, char_);
177 bool operator==(Token const & s, Token const & t)
179 return s.character() == t.character()
180 && s.cat() == t.cat() && s.cs() == t.cs();
183 bool operator!=(Token const & s, Token const & t)
188 ostream & operator<<(ostream & os, Token const & t)
191 os << "\\" << t.cs();
193 os << "[" << t.character() << "," << t.cat() << "]";
202 Parser(LyXLex & lex);
204 Parser(istream & is);
207 string parse_macro();
209 bool parse_normal(MathAtom &);
211 void parse_into(MathArray & array, unsigned flags, MathTextCodes = LM_TC_MIN);
213 int lineno() const { return lineno_; }
219 string getArg(char lf, char rf);
223 void error(string const & msg);
225 bool parse_lines(MathAtom & t, bool numbered, bool outmost);
229 void tokenize(istream & is);
231 void tokenize(string const & s);
233 void push_back(Token const & t);
237 Token const & prevToken() const;
239 Token const & nextToken() const;
241 Token const & getToken();
243 void lex(string const & s);
250 std::vector<Token> tokens_;
262 Parser::Parser(LyXLex & lexer)
263 : lineno_(lexer.getLineNo()), pos_(0), curr_num_(false)
265 tokenize(lexer.getStream());
270 Parser::Parser(istream & is)
271 : lineno_(0), pos_(0), curr_num_(false)
277 void Parser::push_back(Token const & t)
279 tokens_.push_back(t);
283 void Parser::pop_back()
289 Token const & Parser::prevToken() const
291 static const Token dummy;
292 return pos_ > 0 ? tokens_[pos_ - 1] : dummy;
296 Token const & Parser::nextToken() const
298 static const Token dummy;
299 return good() ? tokens_[pos_] : dummy;
303 Token const & Parser::getToken()
305 static const Token dummy;
306 return good() ? tokens_[pos_++] : dummy;
310 void Parser::putback()
316 bool Parser::good() const
318 return pos_ < tokens_.size();
322 char Parser::getChar()
325 lyxerr << "The input stream is not well..." << endl;
326 return tokens_[pos_++].character();
330 string Parser::getArg(char lf, char rg)
338 while ((c = getChar()) != rg && good())
345 void Parser::tokenize(istream & is)
347 // eat everything up to the next \end_inset or end of stream
348 // and store it in s for further tokenization
353 if (s.size() >= 10 && s.substr(s.size() - 10) == "\\end_inset") {
354 s = s.substr(0, s.size() - 10);
364 void Parser::tokenize(string const & buffer)
366 static bool init_done = false;
373 istringstream is(buffer.c_str(), ios::in | ios::binary);
378 switch (catcode(c)) {
382 if (catcode(c) == catNewline)
383 ; //push_back(Token("par"));
385 push_back(Token(' ', catSpace));
392 while (is.get(c) && catcode(c) != catNewline)
401 if (catcode(c) == catLetter) {
402 while (is.get(c) && catcode(c) == catLetter)
404 if (catcode(c) == catSpace)
405 while (is.get(c) && catcode(c) == catSpace)
414 push_back(Token(c, catcode(c)));
419 lyxerr << "\nTokens: ";
420 for (unsigned i = 0; i < tokens_.size(); ++i)
421 lyxerr << tokens_[i];
427 void Parser::error(string const & msg)
429 lyxerr << "Line ~" << lineno_ << ": Math parse error: " << msg << endl;
434 bool Parser::parse_lines(MathAtom & t, bool numbered, bool outmost)
436 MathGridInset * p = t->asGridInset();
438 lyxerr << "error in Parser::parse_lines() 1\n";
442 const int cols = p->ncols();
444 // save global variables
445 bool const saved_num = curr_num_;
446 string const saved_label = curr_label_;
448 for (int row = 0; true; ++row) {
449 // reset global variables
450 curr_num_ = numbered;
454 for (int col = 0; col < cols; ++col) {
455 //lyxerr << "reading cell " << row << " " << col << "\n";
456 parse_into(p->cell(col + row * cols), FLAG_BLOCK);
459 if (prevToken().cat() != catAlign) {
460 //lyxerr << "less cells read than normal in row/col: "
461 // << row << " " << col << "\n";
467 MathMatrixInset * m = t->asMatrixInset();
469 lyxerr << "error in Parser::parse_lines() 2\n";
472 m->numbered(row, curr_num_);
473 m->label(row, curr_label_);
474 if (curr_skip_.size()) {
475 m->vskip(LyXLength(curr_skip_), row);
481 if (prevToken() != Token("\\")) {
482 //lyxerr << "no newline here\n";
489 // restore "global" variables
490 curr_num_ = saved_num;
491 curr_label_ = saved_label;
497 string Parser::parse_macro()
499 string name = "{error}";
501 while (nextToken().cat() == catSpace)
504 if (getToken().cs() != "newcommand") {
505 lyxerr << "\\newcommand expected\n";
509 if (getToken().cat() != catBegin) {
510 lyxerr << "'{' expected\n";
514 name = getToken().cs();
516 if (getToken().cat() != catEnd) {
517 lyxerr << "'}' expected\n";
521 string arg = getArg('[', ']');
522 int narg = arg.empty() ? 0 : atoi(arg.c_str());
524 parse_into(ar, FLAG_BRACE | FLAG_BRACE_LAST);
525 MathMacroTable::create(name, narg, ar);
531 bool Parser::parse_normal(MathAtom & matrix)
533 while (nextToken().cat() == catSpace)
536 Token const & t = getToken();
539 matrix = MathAtom(new MathMatrixInset(LM_OT_SIMPLE));
540 parse_into(matrix->cell(0), 0);
544 if (t.cat() == catMath) {
545 Token const & n = getToken();
546 if (n.cat() == catMath) {
547 // TeX's $$...$$ syntax for displayed math
548 matrix = MathAtom(new MathMatrixInset(LM_OT_EQUATION));
549 MathMatrixInset * p = matrix->asMatrixInset();
550 parse_into(p->cell(0), 0);
551 p->numbered(0, curr_num_);
552 p->label(0, curr_label_);
554 // simple $...$ stuff
556 matrix = MathAtom(new MathMatrixInset(LM_OT_SIMPLE));
557 parse_into(matrix->cell(0), 0);
562 if (!t.cs().size()) {
563 lyxerr << "start of math expected, got '" << t << "'\n";
567 string const & cs = t.cs();
572 matrix = MathAtom(new MathMatrixInset(LM_OT_EQUATION));
573 MathMatrixInset * p = matrix->asMatrixInset();
574 parse_into(p->cell(0), 0);
575 p->numbered(0, curr_num_);
576 p->label(0, curr_label_);
581 lyxerr << "'begin' of un-simple math expected, got '" << cs << "'\n";
585 string const name = getArg('{', '}');
587 if (name == "equation" || name == "equation*") {
588 curr_num_ = !stared(name);
590 matrix = MathAtom(new MathMatrixInset(LM_OT_EQUATION));
591 MathMatrixInset * p = matrix->asMatrixInset();
592 parse_into(p->cell(0), FLAG_END);
593 p->numbered(0, curr_num_);
594 p->label(0, curr_label_);
598 if (name == "eqnarray" || name == "eqnarray*") {
599 matrix = MathAtom(new MathMatrixInset(LM_OT_EQNARRAY));
600 return parse_lines(matrix, !stared(name), true);
603 if (name == "align" || name == "align*") {
604 matrix = MathAtom(new MathMatrixInset(LM_OT_ALIGN));
605 return parse_lines(matrix, !stared(name), true);
608 if (name == "alignat" || name == "alignat*") {
609 int nc = 2 * atoi(getArg('{', '}').c_str());
610 matrix = MathAtom(new MathMatrixInset(LM_OT_ALIGNAT, nc));
611 return parse_lines(matrix, !stared(name), true);
614 if (name == "xalignat" || name == "xalignat*") {
615 int nc = 2 * atoi(getArg('{', '}').c_str());
616 matrix = MathAtom(new MathMatrixInset(LM_OT_XALIGNAT, nc));
617 return parse_lines(matrix, !stared(name), true);
620 if (name == "xxalignat") {
621 int nc = 2 * atoi(getArg('{', '}').c_str());
622 matrix = MathAtom(new MathMatrixInset(LM_OT_XXALIGNAT, nc));
623 return parse_lines(matrix, !stared(name), true);
626 if (name == "multline" || name == "multline*") {
627 matrix = MathAtom(new MathMatrixInset(LM_OT_MULTLINE));
628 return parse_lines(matrix, !stared(name), true);
631 if (name == "gather" || name == "gather*") {
632 matrix = MathAtom(new MathMatrixInset(LM_OT_GATHER));
633 return parse_lines(matrix, !stared(name), true);
636 lyxerr[Debug::MATHED] << "1: unknown math environment: " << name << "\n";
641 void Parser::parse_into(MathArray & array, unsigned flags, MathTextCodes code)
643 MathTextCodes yyvarcode = LM_TC_MIN;
649 Token const & t = getToken();
651 //lyxerr << "t: " << t << " flags: " << flags << "'\n";
652 //array.dump(lyxerr);
655 if (flags & FLAG_ITEM) {
657 if (t.cat() == catBegin) {
658 // skip the brace and collect everything to the next matching
660 flags |= FLAG_BRACE_LAST;
663 // handle only this single token, leave the loop if done
668 if (flags & FLAG_BRACE) {
669 if (t.cat() != catBegin) {
670 error("Expected {. Maybe you forgot to enclose an argument in {}");
674 flags &= ~FLAG_BRACE;
679 if (flags & FLAG_BLOCK) {
680 if (t.cat() == catAlign || t.cs() == "\\")
682 if (t.cs() == "end") {
691 if (t.cat() == catMath)
694 else if (t.cat() == catLetter)
695 add(array, t.character(), yyvarcode);
697 else if (t.cat() == catSpace &&
698 (yyvarcode == LM_TC_TEXTRM || code == LM_TC_TEXTRM))
699 add(array, ' ', yyvarcode);
701 else if (t.cat() == catParameter) {
702 Token const & n = getToken();
703 array.push_back(MathAtom(new MathMacroArgument(n.character() - '0')));
706 else if (t.cat() == catBegin) {
707 add(array, '{', LM_TC_TEX);
710 else if (t.cat() == catEnd) {
711 if (flags & FLAG_BRACE_LAST)
713 add(array, '}', LM_TC_TEX);
716 else if (t.cat() == catAlign) {
717 lyxerr << "found tab unexpectedly, array: '" << array << "'\n";
718 add(array, '&', LM_TC_TEX);
721 else if (t.cat() == catSuper || t.cat() == catSub) {
722 bool up = (t.cat() == catSuper);
723 MathScriptInset * p = 0;
725 p = array.back()->asScriptInset();
726 if (!p || p->has(up)) {
727 array.push_back(MathAtom(new MathScriptInset(up)));
728 p = array.back()->asScriptInset();
731 parse_into(p->cell(up), FLAG_ITEM);
736 else if (t.character() == ']' && (flags & FLAG_BRACK_END))
739 else if (t.cat() == catOther)
740 add(array, t.character(), yyvarcode);
745 else if (t.cs() == "protect")
748 else if (t.cs() == "end")
751 else if (t.cs() == ")")
754 else if (t.cs() == "]")
757 else if (t.cs() == "\\") {
758 curr_skip_ = getArg('[', ']');
759 if (flags & FLAG_NEWLINE)
761 lyxerr[Debug::MATHED]
762 << "found newline unexpectedly, array: '" << array << "'\n";
763 array.push_back(createMathInset("\\"));
766 else if (t.cs() == "limits")
769 else if (t.cs() == "nolimits")
772 else if (t.cs() == "nonumber")
775 else if (t.cs() == "number")
778 else if (t.cs() == "sqrt") {
781 array.push_back(MathAtom(new MathRootInset));
782 parse_into(array.back()->cell(0), FLAG_BRACK_END);
783 parse_into(array.back()->cell(1), FLAG_ITEM);
786 array.push_back(MathAtom(new MathSqrtInset));
787 parse_into(array.back()->cell(0), FLAG_ITEM);
791 else if (t.cs() == "left") {
792 string l = getToken().asString();
794 parse_into(ar, FLAG_RIGHT);
795 string r = getToken().asString();
796 MathAtom dl(new MathDelimInset(l, r));
801 else if (t.cs() == "right") {
802 if (!(flags & FLAG_RIGHT)) {
803 lyxerr << "got so far: '" << array << "'\n";
804 error("Unmatched right delimiter");
812 lyxerr[Debug::MATHED] << "LM_TK_STY not implemented\n";
813 //MathArray tmp = array;
814 //MathSizeInset * p = new MathSizeInset(MathStyles(lval_->id));
815 //array.push_back(p);
816 //parse_into(p->cell(0), FLAG_BRACE_FONT);
822 else if (t.cs() == "begin") {
823 string const name = getArg('{', '}');
824 if (name == "array") {
825 string const valign = getArg('[', ']') + 'c';
826 string const halign = getArg('{', '}');
828 MathAtom(new MathArrayInset(halign.size(), 1, valign[0], halign)));
829 parse_lines(array.back(), false, false);
830 } else if (name == "split") {
831 array.push_back(MathAtom(new MathSplitInset(1)));
832 parse_lines(array.back(), false, false);
834 lyxerr[Debug::MATHED] << "unknow math inset begin '" << name << "'\n";
837 else if (t.cs() == "kern") {
843 Token const & t = getToken();
849 if (isValidLength(s))
852 array.push_back(MathAtom(new MathKernInset(s)));
855 else if (t.cs() == "label") {
857 //parse_into(ar, FLAG_ITEM);
859 //ar.write(os, true);
860 //curr_label_ = os.str();
862 curr_label_ = getArg('{', '}');
865 else if (t.cs() == "choose" || t.cs() == "over" || t.cs() == "atop") {
866 MathAtom p = createMathInset(t.cs());
867 // search backward for position of last '{' if any
869 for (pos = array.size() - 1; pos >= 0; --pos)
870 if (array.at(pos)->getChar() == '{')
873 // found it -> use the part after '{' as "numerator"
874 p->cell(0) = MathArray(array, pos + 1, array.size());
875 parse_into(p->cell(1), FLAG_BRACE_LAST);
876 // delete denominator and the '{'
877 array.erase(pos, array.size());
878 } else if (flags & FLAG_RIGHT) {
879 // we are inside a \left ... \right block
880 //lyxerr << "found '" << t.cs() << "' enclosed by \\left .. \\right\n";
881 p->cell(0).swap(array);
882 parse_into(p->cell(1), FLAG_RIGHT);
883 // handle the right delimiter properly
886 // not found -> use everything as "numerator"
887 p->cell(0).swap(array);
888 parse_into(p->cell(1), FLAG_BLOCK);
890 array.push_back(MathAtom(p));
893 else if (t.cs().size()) {
894 latexkeys const * l = in_word_set(t.cs());
896 if (l->token == LM_TK_FONT) {
897 //lyxerr << "starting font\n";
898 //CatCode catSpaceSave = theCatcode[' '];
899 //if (l->id == LM_TC_TEXTRM) {
900 // // temporarily change catcode
901 // theCatcode[' '] = catLetter;
904 MathTextCodes t = static_cast<MathTextCodes>(l->id);
906 parse_into(ar, FLAG_ITEM, t);
907 for (MathArray::iterator it = ar.begin(); it != ar.end(); ++it)
908 (*it)->handleFont(t);
911 // undo catcode changes
912 ////theCatcode[' '] = catSpaceSave;
913 //lyxerr << "ending font\n";
916 else if (l->token == LM_TK_OLDFONT)
917 yyvarcode = static_cast<MathTextCodes>(l->id);
920 MathAtom p = createMathInset(t.cs());
921 for (MathInset::idx_type i = 0; i < p->nargs(); ++i)
922 parse_into(p->cell(i), FLAG_ITEM);
928 MathAtom p = createMathInset(t.cs());
929 for (MathInset::idx_type i = 0; i < p->nargs(); ++i)
930 parse_into(p->cell(i), FLAG_ITEM);
936 if (flags & FLAG_LEAVE) {
937 flags &= ~FLAG_LEAVE;
943 lyxerr << " Math Panic, expect problems!\n";
944 // Search for the end command.
948 } while (good() && t.cs() != "end");
954 } // anonymous namespace
958 MathArray mathed_parse_cell(string const & str)
960 istringstream is(str.c_str());
963 parser.parse_into(ar, 0);
969 string mathed_parse_macro(string const & str)
971 istringstream is(str.c_str());
973 return parser.parse_macro();
976 string mathed_parse_macro(istream & is)
979 return parser.parse_macro();
982 string mathed_parse_macro(LyXLex & lex)
985 return parser.parse_macro();
990 bool mathed_parse_normal(MathAtom & t, string const & str)
992 istringstream is(str.c_str());
994 return parser.parse_normal(t);
997 bool mathed_parse_normal(MathAtom & t, istream & is)
1000 return parser.parse_normal(t);
1003 bool mathed_parse_normal(MathAtom & t, LyXLex & lex)
1006 return parser.parse_normal(t);