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();
538 if (t.cat() == catMath || t.cs() == "(") {
539 matrix = MathAtom(new MathMatrixInset(LM_OT_SIMPLE));
540 parse_into(matrix->cell(0), 0);
544 if (!t.cs().size()) {
545 lyxerr << "start of math expected, got '" << t << "'\n";
549 string const & cs = t.cs();
554 matrix = MathAtom(new MathMatrixInset(LM_OT_EQUATION));
555 MathMatrixInset * p = matrix->asMatrixInset();
556 parse_into(p->cell(0), 0);
557 p->numbered(0, curr_num_);
558 p->label(0, curr_label_);
563 lyxerr << "'begin' of un-simple math expected, got '" << cs << "'\n";
567 string const name = getArg('{', '}');
569 if (name == "equation" || name == "equation*") {
570 curr_num_ = !stared(name);
572 matrix = MathAtom(new MathMatrixInset(LM_OT_EQUATION));
573 MathMatrixInset * p = matrix->asMatrixInset();
574 parse_into(p->cell(0), FLAG_END);
575 p->numbered(0, curr_num_);
576 p->label(0, curr_label_);
580 if (name == "eqnarray" || name == "eqnarray*") {
581 matrix = MathAtom(new MathMatrixInset(LM_OT_EQNARRAY));
582 return parse_lines(matrix, !stared(name), true);
585 if (name == "align" || name == "align*") {
586 matrix = MathAtom(new MathMatrixInset(LM_OT_ALIGN));
587 return parse_lines(matrix, !stared(name), true);
590 if (name == "alignat" || name == "alignat*") {
591 int nc = 2 * atoi(getArg('{', '}').c_str());
592 matrix = MathAtom(new MathMatrixInset(LM_OT_ALIGNAT, nc));
593 return parse_lines(matrix, !stared(name), true);
596 if (name == "xalignat" || name == "xalignat*") {
597 int nc = 2 * atoi(getArg('{', '}').c_str());
598 matrix = MathAtom(new MathMatrixInset(LM_OT_XALIGNAT, nc));
599 return parse_lines(matrix, !stared(name), true);
602 if (name == "xxalignat") {
603 int nc = 2 * atoi(getArg('{', '}').c_str());
604 matrix = MathAtom(new MathMatrixInset(LM_OT_XXALIGNAT, nc));
605 return parse_lines(matrix, !stared(name), true);
608 if (name == "multline" || name == "multline*") {
609 matrix = MathAtom(new MathMatrixInset(LM_OT_MULTLINE));
610 return parse_lines(matrix, !stared(name), true);
613 if (name == "gather" || name == "gather*") {
614 matrix = MathAtom(new MathMatrixInset(LM_OT_GATHER));
615 return parse_lines(matrix, !stared(name), true);
618 lyxerr[Debug::MATHED] << "1: unknown math environment: " << name << "\n";
623 void Parser::parse_into(MathArray & array, unsigned flags, MathTextCodes code)
625 MathTextCodes yyvarcode = LM_TC_MIN;
631 Token const & t = getToken();
633 //lyxerr << "t: " << t << " flags: " << flags << "'\n";
634 //array.dump(lyxerr);
637 if (flags & FLAG_ITEM) {
639 if (t.cat() == catBegin) {
640 // skip the brace and collect everything to the next matching
642 flags |= FLAG_BRACE_LAST;
645 // handle only this single token, leave the loop if done
650 if (flags & FLAG_BRACE) {
651 if (t.cat() != catBegin) {
652 error("Expected {. Maybe you forgot to enclose an argument in {}");
656 flags &= ~FLAG_BRACE;
661 if (flags & FLAG_BLOCK) {
662 if (t.cat() == catAlign || t.cs() == "\\")
664 if (t.cs() == "end") {
673 if (t.cat() == catMath)
676 else if (t.cat() == catLetter)
677 add(array, t.character(), yyvarcode);
679 else if (t.cat() == catSpace &&
680 (yyvarcode == LM_TC_TEXTRM || code == LM_TC_TEXTRM))
681 add(array, ' ', yyvarcode);
683 else if (t.cat() == catParameter) {
684 Token const & n = getToken();
685 array.push_back(MathAtom(new MathMacroArgument(n.character() - '0')));
688 else if (t.cat() == catBegin) {
689 add(array, '{', LM_TC_TEX);
692 else if (t.cat() == catEnd) {
693 if (flags & FLAG_BRACE_LAST)
695 add(array, '}', LM_TC_TEX);
698 else if (t.cat() == catAlign) {
699 lyxerr << "found tab unexpectedly, array: '" << array << "'\n";
700 add(array, '&', LM_TC_TEX);
703 else if (t.cat() == catSuper || t.cat() == catSub) {
704 bool up = (t.cat() == catSuper);
705 MathScriptInset * p = 0;
707 p = array.back()->asScriptInset();
708 if (!p || p->has(up)) {
709 array.push_back(MathAtom(new MathScriptInset(up)));
710 p = array.back()->asScriptInset();
713 parse_into(p->cell(up), FLAG_ITEM);
718 else if (t.character() == ']' && (flags & FLAG_BRACK_END))
721 else if (t.cat() == catOther)
722 add(array, t.character(), yyvarcode);
727 else if (t.cs() == "protect")
730 else if (t.cs() == "end")
733 else if (t.cs() == ")")
736 else if (t.cs() == "]")
739 else if (t.cs() == "\\") {
740 curr_skip_ = getArg('[', ']');
741 if (flags & FLAG_NEWLINE)
743 lyxerr[Debug::MATHED]
744 << "found newline unexpectedly, array: '" << array << "'\n";
745 array.push_back(createMathInset("\\"));
748 else if (t.cs() == "limits")
751 else if (t.cs() == "nolimits")
754 else if (t.cs() == "nonumber")
757 else if (t.cs() == "number")
760 else if (t.cs() == "sqrt") {
763 array.push_back(MathAtom(new MathRootInset));
764 parse_into(array.back()->cell(0), FLAG_BRACK_END);
765 parse_into(array.back()->cell(1), FLAG_ITEM);
768 array.push_back(MathAtom(new MathSqrtInset));
769 parse_into(array.back()->cell(0), FLAG_ITEM);
773 else if (t.cs() == "left") {
774 string l = getToken().asString();
776 parse_into(ar, FLAG_RIGHT);
777 string r = getToken().asString();
778 MathAtom dl(new MathDelimInset(l, r));
783 else if (t.cs() == "right") {
784 if (!(flags & FLAG_RIGHT)) {
785 lyxerr << "got so far: '" << array << "'\n";
786 error("Unmatched right delimiter");
794 lyxerr[Debug::MATHED] << "LM_TK_STY not implemented\n";
795 //MathArray tmp = array;
796 //MathSizeInset * p = new MathSizeInset(MathStyles(lval_->id));
797 //array.push_back(p);
798 //parse_into(p->cell(0), FLAG_BRACE_FONT);
804 else if (t.cs() == "begin") {
805 string const name = getArg('{', '}');
806 if (name == "array") {
807 string const valign = getArg('[', ']') + 'c';
808 string const halign = getArg('{', '}');
810 MathAtom(new MathArrayInset(halign.size(), 1, valign[0], halign)));
811 parse_lines(array.back(), false, false);
812 } else if (name == "split") {
813 array.push_back(MathAtom(new MathSplitInset(1)));
814 parse_lines(array.back(), false, false);
816 lyxerr[Debug::MATHED] << "unknow math inset begin '" << name << "'\n";
819 else if (t.cs() == "kern") {
825 Token const & t = getToken();
831 if (isValidLength(s))
834 array.push_back(MathAtom(new MathKernInset(s)));
837 else if (t.cs() == "label") {
839 //parse_into(ar, FLAG_ITEM);
841 //ar.write(os, true);
842 //curr_label_ = os.str();
844 curr_label_ = getArg('{', '}');
847 else if (t.cs() == "choose" || t.cs() == "over" || t.cs() == "atop") {
848 MathAtom p = createMathInset(t.cs());
849 // search backward for position of last '{' if any
851 for (pos = array.size() - 1; pos >= 0; --pos)
852 if (array.at(pos)->getChar() == '{')
855 // found it -> use the part after '{' as "numerator"
856 p->cell(0) = MathArray(array, pos + 1, array.size());
857 parse_into(p->cell(1), FLAG_BRACE_LAST);
858 // delete denominator and the '{'
859 array.erase(pos, array.size());
860 } else if (flags & FLAG_RIGHT) {
861 // we are inside a \left ... \right block
862 //lyxerr << "found '" << t.cs() << "' enclosed by \\left .. \\right\n";
863 p->cell(0).swap(array);
864 parse_into(p->cell(1), FLAG_RIGHT);
865 // handle the right delimiter properly
868 // not found -> use everything as "numerator"
869 p->cell(0).swap(array);
870 parse_into(p->cell(1), FLAG_BLOCK);
872 array.push_back(MathAtom(p));
875 else if (t.cs().size()) {
876 latexkeys const * l = in_word_set(t.cs());
878 if (l->token == LM_TK_FONT) {
879 //lyxerr << "starting font\n";
880 //CatCode catSpaceSave = theCatcode[' '];
881 //if (l->id == LM_TC_TEXTRM) {
882 // // temporarily change catcode
883 // theCatcode[' '] = catLetter;
886 MathTextCodes t = static_cast<MathTextCodes>(l->id);
888 parse_into(ar, FLAG_ITEM, t);
889 for (MathArray::iterator it = ar.begin(); it != ar.end(); ++it)
890 (*it)->handleFont(t);
893 // undo catcode changes
894 ////theCatcode[' '] = catSpaceSave;
895 //lyxerr << "ending font\n";
898 else if (l->token == LM_TK_OLDFONT)
899 yyvarcode = static_cast<MathTextCodes>(l->id);
902 MathAtom p = createMathInset(t.cs());
903 for (MathInset::idx_type i = 0; i < p->nargs(); ++i)
904 parse_into(p->cell(i), FLAG_ITEM);
910 MathAtom p = createMathInset(t.cs());
911 for (MathInset::idx_type i = 0; i < p->nargs(); ++i)
912 parse_into(p->cell(i), FLAG_ITEM);
918 if (flags & FLAG_LEAVE) {
919 flags &= ~FLAG_LEAVE;
925 lyxerr << " Math Panic, expect problems!\n";
926 // Search for the end command.
930 } while (good() && t.cs() != "end");
936 } // anonymous namespace
940 MathArray mathed_parse_cell(string const & str)
942 istringstream is(str.c_str());
945 parser.parse_into(ar, 0);
951 string mathed_parse_macro(string const & str)
953 istringstream is(str.c_str());
955 return parser.parse_macro();
958 string mathed_parse_macro(istream & is)
961 return parser.parse_macro();
964 string mathed_parse_macro(LyXLex & lex)
967 return parser.parse_macro();
972 bool mathed_parse_normal(MathAtom & t, string const & str)
974 istringstream is(str.c_str());
976 return parser.parse_normal(t);
979 bool mathed_parse_normal(MathAtom & t, istream & is)
982 return parser.parse_normal(t);
985 bool mathed_parse_normal(MathAtom & t, LyXLex & lex)
988 return parser.parse_normal(t);