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.
20 If someone desperately needs partial "structures" (such as a few cells of
21 an array inset or similar) (s)he could uses the following hack as starting
22 point to write some macros:
27 \def\makeamptab{\catcode`\&=4\relax}
28 \def\makeampletter{\catcode`\&=11\relax}
29 \def\b{\makeampletter\expandafter\makeamptab\bi}
49 #pragma implementation
52 #include "math_parser.h"
53 #include "math_inset.h"
54 #include "math_arrayinset.h"
55 #include "math_braceinset.h"
56 #include "math_casesinset.h"
57 #include "math_charinset.h"
58 #include "math_deliminset.h"
59 #include "math_factory.h"
60 #include "math_funcinset.h"
61 #include "math_kerninset.h"
62 #include "math_macro.h"
63 #include "math_macrotable.h"
64 #include "math_macrotemplate.h"
65 #include "math_hullinset.h"
66 #include "math_rootinset.h"
67 #include "math_sizeinset.h"
68 #include "math_sqrtinset.h"
69 #include "math_scriptinset.h"
70 #include "math_specialcharinset.h"
71 #include "math_splitinset.h"
72 #include "math_sqrtinset.h"
73 #include "math_support.h"
78 #include "support/lstrings.h"
94 bool stared(string const & s)
96 string::size_type const n = s.size();
97 return n && s[n - 1] == '*';
101 void add(MathArray & ar, char c, MathTextCodes code)
103 ar.push_back(MathAtom(new MathCharInset(c, code)));
107 // These are TeX's catcodes
109 catEscape, // 0 backslash
119 catSpace, // 10 space
120 catLetter, // 11 a-zA-Z
121 catOther, // 12 none of the above
124 catInvalid // 15 <delete>
127 CatCode theCatcode[256];
130 inline CatCode catcode(unsigned char c)
132 return theCatcode[c];
137 FLAG_BRACE_LAST = 1 << 1, // last closing brace ends the parsing process
138 FLAG_RIGHT = 1 << 2, // next \\right ends the parsing process
139 FLAG_END = 1 << 3, // next \\end ends the parsing process
140 FLAG_BRACK_END = 1 << 4, // next closing bracket ends the parsing process
141 FLAG_BOX = 1 << 5, // we are in a box
142 FLAG_ITEM = 1 << 7, // read a (possibly braced token)
143 FLAG_BLOCK = 1 << 8, // next block ends the parsing process
144 FLAG_LEAVE = 1 << 9 // leave the loop at the end
150 fill(theCatcode, theCatcode + 256, catOther);
151 fill(theCatcode + 'a', theCatcode + 'z' + 1, catLetter);
152 fill(theCatcode + 'A', theCatcode + 'Z' + 1, catLetter);
154 theCatcode['\\'] = catEscape;
155 theCatcode['{'] = catBegin;
156 theCatcode['}'] = catEnd;
157 theCatcode['$'] = catMath;
158 theCatcode['&'] = catAlign;
159 theCatcode['\n'] = catNewline;
160 theCatcode['#'] = catParameter;
161 theCatcode['^'] = catSuper;
162 theCatcode['_'] = catSub;
163 theCatcode['
\7f'] = catIgnore;
164 theCatcode[' '] = catSpace;
165 theCatcode['\t'] = catSpace;
166 theCatcode['\r'] = catSpace;
167 theCatcode['~'] = catActive;
168 theCatcode['%'] = catComment;
174 // Helper class for parsing
180 Token() : cs_(), char_(0), cat_(catIgnore) {}
182 Token(char c, CatCode cat) : cs_(), char_(c), cat_(cat) {}
184 Token(string const & cs) : cs_(cs), char_(0), cat_(catIgnore) {}
187 string const & cs() const { return cs_; }
189 CatCode cat() const { return cat_; }
191 char character() const { return char_; }
193 string asString() const;
206 bool Token::isCR() const
208 return cs_ == "\\" || cs_ == "cr" || cs_ == "crcr";
211 string Token::asString() const
213 return cs_.size() ? cs_ : string(1, char_);
216 // Angus' compiler says these are not needed
217 //bool operator==(Token const & s, Token const & t)
219 // return s.character() == t.character()
220 // && s.cat() == t.cat() && s.cs() == t.cs();
223 //bool operator!=(Token const & s, Token const & t)
228 ostream & operator<<(ostream & os, Token const & t)
231 os << "\\" << t.cs();
233 os << "[" << t.character() << "," << t.cat() << "]";
242 Parser(LyXLex & lex);
244 Parser(istream & is);
247 bool parse_macro(string & name);
249 bool parse_normal(MathAtom &);
251 void parse_into(MathArray & array, unsigned flags, MathTextCodes = LM_TC_MIN);
253 int lineno() const { return lineno_; }
259 string getArg(char lf, char rf);
263 void error(string const & msg);
265 bool parse_lines(MathAtom & t, bool numbered, bool outmost);
269 void tokenize(istream & is);
271 void tokenize(string const & s);
273 void push_back(Token const & t);
277 Token const & prevToken() const;
279 Token const & nextToken() const;
281 Token const & getToken();
282 /// skips spaces if any
284 /// counts a sequence of hlines
287 void lex(string const & s);
294 std::vector<Token> tokens_;
306 Parser::Parser(LyXLex & lexer)
307 : lineno_(lexer.getLineNo()), pos_(0), curr_num_(false)
309 tokenize(lexer.getStream());
314 Parser::Parser(istream & is)
315 : lineno_(0), pos_(0), curr_num_(false)
321 void Parser::push_back(Token const & t)
323 tokens_.push_back(t);
327 void Parser::pop_back()
333 Token const & Parser::prevToken() const
335 static const Token dummy;
336 return pos_ > 0 ? tokens_[pos_ - 1] : dummy;
340 Token const & Parser::nextToken() const
342 static const Token dummy;
343 return good() ? tokens_[pos_] : dummy;
347 Token const & Parser::getToken()
349 static const Token dummy;
350 //lyxerr << "looking at token " << tokens_[pos_] << '\n';
351 return good() ? tokens_[pos_++] : dummy;
355 void Parser::skipSpaces()
357 while (nextToken().cat() == catSpace)
362 int Parser::readHLines()
366 while (nextToken().cs() == "hline") {
375 void Parser::putback()
381 bool Parser::good() const
383 return pos_ < tokens_.size();
387 char Parser::getChar()
390 lyxerr << "The input stream is not well..." << endl;
391 return tokens_[pos_++].character();
395 string Parser::getArg(char lf, char rg)
403 while ((c = getChar()) != rg && good())
410 void Parser::tokenize(istream & is)
412 // eat everything up to the next \end_inset or end of stream
413 // and store it in s for further tokenization
418 if (s.size() >= 10 && s.substr(s.size() - 10) == "\\end_inset") {
419 s = s.substr(0, s.size() - 10);
429 void Parser::tokenize(string const & buffer)
431 static bool init_done = false;
438 istringstream is(buffer.c_str(), ios::in | ios::binary);
443 switch (catcode(c)) {
447 if (catcode(c) == catNewline)
448 ; //push_back(Token("par"));
450 push_back(Token(' ', catSpace));
457 while (is.get(c) && catcode(c) != catNewline)
466 if (catcode(c) == catLetter) {
467 while (is.get(c) && catcode(c) == catLetter)
469 if (catcode(c) == catSpace)
470 while (is.get(c) && catcode(c) == catSpace)
479 push_back(Token(c, catcode(c)));
484 lyxerr << "\nTokens: ";
485 for (unsigned i = 0; i < tokens_.size(); ++i)
486 lyxerr << tokens_[i];
492 void Parser::error(string const & msg)
494 lyxerr << "Line ~" << lineno_ << ": Math parse error: " << msg << endl;
499 bool Parser::parse_lines(MathAtom & t, bool numbered, bool outmost)
501 MathGridInset * p = t->asGridInset();
503 lyxerr << "error in Parser::parse_lines() 1\n";
507 MathInset::col_type const cols = p->ncols();
509 // save global variables
510 bool const saved_num = curr_num_;
511 string const saved_label = curr_label_;
513 // read initial hlines
514 p->rowinfo(0).lines_ = readHLines();
516 for (int row = 0; true; ++row) {
517 // reset global variables
518 curr_num_ = numbered;
522 for (MathInset::col_type col = 0; col < cols; ++col) {
523 //lyxerr << "reading cell " << row << " " << col << "\n";
524 parse_into(p->cell(col + row * cols), FLAG_BLOCK);
526 // break if cell is not followed by an ampersand
527 if (nextToken().cat() != catAlign) {
528 //lyxerr << "less cells read than normal in row/col: "
529 // << row << " " << col << "\n";
533 // skip the ampersand
538 MathHullInset * m = t->asHullInset();
540 lyxerr << "error in Parser::parse_lines() 2\n";
543 m->numbered(row, curr_num_);
544 m->label(row, curr_label_);
545 if (curr_skip_.size()) {
546 m->vcrskip(LyXLength(curr_skip_), row);
552 if (nextToken().isCR()) {
556 // try to read a length
559 // read hlines for next row
560 p->rowinfo(row + 1).lines_ = readHLines();
563 // we are finished if the next token is an 'end'
564 if (nextToken().cs() == "end") {
565 // skip the end-token
569 // leave the 'read a line'-loop
573 // otherwise, we have to start a new row
577 // restore "global" variables
578 curr_num_ = saved_num;
579 curr_label_ = saved_label;
585 bool Parser::parse_macro(string & name)
590 if (getToken().cs() != "newcommand") {
591 lyxerr << "\\newcommand expected\n";
595 if (getToken().cat() != catBegin) {
596 lyxerr << "'{' in \\newcommand expected (1)\n";
600 name = getToken().cs();
602 if (getToken().cat() != catEnd) {
603 lyxerr << "'}' expected\n";
607 string arg = getArg('[', ']');
608 int narg = arg.empty() ? 0 : atoi(arg.c_str());
610 if (getToken().cat() != catBegin) {
611 lyxerr << "'{' in \\newcommand expected (2)\n";
616 parse_into(ar, FLAG_BRACE_LAST);
618 // we cannot handle recursive stuff at all
620 test.push_back(createMathInset(name));
621 if (ar.contains(test)) {
622 lyxerr << "we cannot handle recursive macros at all.\n";
626 MathMacroTable::create(name, narg, ar);
631 bool Parser::parse_normal(MathAtom & matrix)
634 Token const & t = getToken();
637 matrix = MathAtom(new MathHullInset(LM_OT_SIMPLE));
638 parse_into(matrix->cell(0), 0);
642 if (t.cat() == catMath) {
643 Token const & n = getToken();
644 if (n.cat() == catMath) {
645 // TeX's $$...$$ syntax for displayed math
646 matrix = MathAtom(new MathHullInset(LM_OT_EQUATION));
647 MathHullInset * p = matrix->asHullInset();
648 parse_into(p->cell(0), 0);
649 p->numbered(0, curr_num_);
650 p->label(0, curr_label_);
652 // simple $...$ stuff
654 matrix = MathAtom(new MathHullInset(LM_OT_SIMPLE));
655 parse_into(matrix->cell(0), 0);
660 if (!t.cs().size()) {
661 lyxerr << "start of math expected, got '" << t << "'\n";
665 string const & cs = t.cs();
670 matrix = MathAtom(new MathHullInset(LM_OT_EQUATION));
671 MathHullInset * p = matrix->asHullInset();
672 parse_into(p->cell(0), 0);
673 p->numbered(0, curr_num_);
674 p->label(0, curr_label_);
679 lyxerr << "'begin' of un-simple math expected, got '" << cs << "'\n";
683 string const name = getArg('{', '}');
685 if (name == "math") {
686 matrix = MathAtom(new MathHullInset(LM_OT_SIMPLE));
687 parse_into(matrix->cell(0), 0);
691 if (name == "equation" || name == "equation*" || name == "displaymath") {
692 curr_num_ = (name == "equation");
694 matrix = MathAtom(new MathHullInset(LM_OT_EQUATION));
695 MathHullInset * p = matrix->asHullInset();
696 parse_into(p->cell(0), FLAG_END);
697 p->numbered(0, curr_num_);
698 p->label(0, curr_label_);
702 if (name == "eqnarray" || name == "eqnarray*") {
703 matrix = MathAtom(new MathHullInset(LM_OT_EQNARRAY));
704 return parse_lines(matrix, !stared(name), true);
707 if (name == "align" || name == "align*") {
708 matrix = MathAtom(new MathHullInset(LM_OT_ALIGN));
709 return parse_lines(matrix, !stared(name), true);
712 if (name == "alignat" || name == "alignat*") {
713 int nc = 2 * atoi(getArg('{', '}').c_str());
714 matrix = MathAtom(new MathHullInset(LM_OT_ALIGNAT, nc));
715 return parse_lines(matrix, !stared(name), true);
718 if (name == "xalignat" || name == "xalignat*") {
719 int nc = 2 * atoi(getArg('{', '}').c_str());
720 matrix = MathAtom(new MathHullInset(LM_OT_XALIGNAT, nc));
721 return parse_lines(matrix, !stared(name), true);
724 if (name == "xxalignat") {
725 int nc = 2 * atoi(getArg('{', '}').c_str());
726 matrix = MathAtom(new MathHullInset(LM_OT_XXALIGNAT, nc));
727 return parse_lines(matrix, !stared(name), true);
730 if (name == "multline" || name == "multline*") {
731 matrix = MathAtom(new MathHullInset(LM_OT_MULTLINE));
732 return parse_lines(matrix, !stared(name), true);
735 if (name == "gather" || name == "gather*") {
736 matrix = MathAtom(new MathHullInset(LM_OT_GATHER));
737 return parse_lines(matrix, !stared(name), true);
740 lyxerr[Debug::MATHED] << "1: unknown math environment: " << name << "\n";
741 lyxerr << "1: unknown math environment: " << name << "\n";
746 void Parser::parse_into(MathArray & array, unsigned flags, MathTextCodes code)
752 Token const & t = getToken();
754 //lyxerr << "t: " << t << " flags: " << flags << "'\n";
755 //array.dump(lyxerr);
758 if (flags & FLAG_ITEM) {
760 if (t.cat() == catBegin) {
761 // skip the brace and collect everything to the next matching
763 flags |= FLAG_BRACE_LAST;
766 // handle only this single token, leave the loop if done
771 if (flags & FLAG_BLOCK) {
772 if (t.cat() == catAlign || t.isCR() || t.cs() == "end") {
781 if (t.cat() == catMath) {
782 if (flags & FLAG_BOX) {
783 // we are inside an mbox, so opening new math is allowed
784 array.push_back(MathAtom(new MathHullInset(LM_OT_SIMPLE)));
785 parse_into(array.back()->cell(0), 0);
787 // otherwise this is the end of the formula
792 else if (t.cat() == catLetter)
793 add(array, t.character(), code);
795 else if (t.cat() == catSpace && code == LM_TC_TEXTRM)
796 add(array, t.character(), code);
798 else if (t.cat() == catParameter) {
799 Token const & n = getToken();
800 array.push_back(MathAtom(new MathMacroArgument(n.character()-'0', code)));
803 else if (t.cat() == catBegin) {
805 parse_into(ar, FLAG_BRACE_LAST);
806 #ifndef WITH_WARNINGS
807 #warning this might be wrong in general!
809 // ignore braces around simple items
810 if ((ar.size() == 1 && !ar.front()->needsBraces()
811 || (ar.size() == 2 && !ar.front()->needsBraces()
812 && ar.back()->asScriptInset()))
813 || (ar.size() == 0 && array.size() == 0))
817 array.push_back(MathAtom(new MathBraceInset));
818 array.back()->cell(0).swap(ar);
822 else if (t.cat() == catEnd) {
823 if (flags & FLAG_BRACE_LAST)
825 lyxerr << "found '}' unexpectedly, array: '" << array << "'\n";
826 //lyxerr << "found '}' unexpectedly\n";
827 add(array, '}', LM_TC_TEX);
830 else if (t.cat() == catAlign) {
831 lyxerr << "found tab unexpectedly, array: '" << array << "'\n";
832 //lyxerr << "found tab unexpectedly\n";
833 add(array, '&', LM_TC_TEX);
836 else if (t.cat() == catSuper || t.cat() == catSub) {
837 bool up = (t.cat() == catSuper);
838 MathScriptInset * p = 0;
840 p = array.back()->asScriptInset();
841 if (!p || p->has(up)) {
842 array.push_back(MathAtom(new MathScriptInset(up)));
843 p = array.back()->asScriptInset();
846 parse_into(p->cell(up), FLAG_ITEM);
851 else if (t.character() == ']' && (flags & FLAG_BRACK_END))
854 else if (t.cat() == catOther)
855 add(array, t.character(), code);
860 else if (t.cs() == "protect")
861 // ignore \\protect, will be re-added during output
864 else if (t.cs() == "end")
867 else if (t.cs() == ")")
870 else if (t.cs() == "]")
873 else if (t.cs() == "\\") {
874 curr_skip_ = getArg('[', ']');
875 //lyxerr << "found newline unexpectedly, array: '" << array << "'\n";
876 lyxerr << "found newline unexpectedly\n";
877 array.push_back(createMathInset("\\"));
880 else if (t.cs() == "limits")
883 else if (t.cs() == "nolimits")
886 else if (t.cs() == "nonumber")
889 else if (t.cs() == "number")
892 else if (t.cs() == "sqrt") {
895 array.push_back(MathAtom(new MathRootInset));
896 parse_into(array.back()->cell(0), FLAG_BRACK_END);
897 parse_into(array.back()->cell(1), FLAG_ITEM);
900 array.push_back(MathAtom(new MathSqrtInset));
901 parse_into(array.back()->cell(0), FLAG_ITEM);
905 else if (t.cs() == "left") {
906 string l = getToken().asString();
908 parse_into(ar, FLAG_RIGHT);
909 string r = getToken().asString();
910 MathAtom dl(new MathDelimInset(l, r));
915 else if (t.cs() == "right") {
916 if (!(flags & FLAG_RIGHT)) {
917 //lyxerr << "got so far: '" << array << "'\n";
918 error("Unmatched right delimiter");
923 else if (t.cs() == "begin") {
924 string const name = getArg('{', '}');
925 if (name == "array") {
926 string const valign = getArg('[', ']') + 'c';
927 string const halign = getArg('{', '}');
928 array.push_back(MathAtom(new MathArrayInset(valign[0], halign)));
929 parse_lines(array.back(), false, false);
930 } else if (name == "split") {
931 array.push_back(MathAtom(new MathSplitInset(1)));
932 parse_lines(array.back(), false, false);
933 } else if (name == "cases") {
934 array.push_back(MathAtom(new MathCasesInset));
935 parse_lines(array.back(), false, false);
937 lyxerr << "unknow math inset begin '" << name << "'\n";
940 else if (t.cs() == "kern") {
946 Token const & t = getToken();
952 if (isValidLength(s))
955 array.push_back(MathAtom(new MathKernInset(s)));
958 else if (t.cs() == "label") {
959 curr_label_ = getArg('{', '}');
962 else if (t.cs() == "choose" || t.cs() == "over" || t.cs() == "atop") {
963 MathAtom p = createMathInset(t.cs());
964 array.swap(p->cell(0));
965 parse_into(p->cell(1), flags, code);
972 else if (t.cs() == "mbox") {
973 array.push_back(createMathInset(t.cs()));
974 // slurp in the argument of mbox
976 MathBoxInset * p = array.back()->asBoxInset();
982 else if (t.cs().size()) {
983 latexkeys const * l = in_word_set(t.cs());
985 if (l->token == LM_TK_FONT) {
986 //lyxerr << "starting font\n";
987 //CatCode catSpaceSave = theCatcode[' '];
988 //if (l->id == LM_TC_TEXTRM) {
989 // // temporarily change catcode
990 // theCatcode[' '] = catLetter;
994 parse_into(ar, FLAG_ITEM, static_cast<MathTextCodes>(l->id));
997 // undo catcode changes
998 ////theCatcode[' '] = catSpaceSave;
999 //lyxerr << "ending font\n";
1002 else if (l->token == LM_TK_OLDFONT) {
1003 code = static_cast<MathTextCodes>(l->id);
1006 else if (l->token == LM_TK_BOX) {
1007 MathAtom p = createMathInset(t.cs());
1008 parse_into(p->cell(0), FLAG_ITEM | FLAG_BOX, LM_TC_BOX);
1012 else if (l->token == LM_TK_STY) {
1013 MathAtom p = createMathInset(t.cs());
1014 parse_into(p->cell(0), flags, code);
1020 MathAtom p = createMathInset(t.cs());
1021 for (MathInset::idx_type i = 0; i < p->nargs(); ++i)
1022 parse_into(p->cell(i), FLAG_ITEM);
1028 MathAtom p = createMathInset(t.cs());
1029 for (MathInset::idx_type i = 0; i < p->nargs(); ++i)
1030 parse_into(p->cell(i), FLAG_ITEM);
1036 if (flags & FLAG_LEAVE) {
1037 flags &= ~FLAG_LEAVE;
1043 lyxerr << " Math Panic, expect problems!\n";
1044 // Search for the end command.
1048 } while (good() && t.cs() != "end");
1054 } // anonymous namespace
1057 void mathed_parse_cell(MathArray & ar, string const & str)
1059 istringstream is(str.c_str());
1060 mathed_parse_cell(ar, is);
1064 void mathed_parse_cell(MathArray & ar, istream & is)
1066 Parser(is).parse_into(ar, 0);
1071 bool mathed_parse_macro(string & name, string const & str)
1073 istringstream is(str.c_str());
1075 return parser.parse_macro(name);
1078 bool mathed_parse_macro(string & name, istream & is)
1081 return parser.parse_macro(name);
1084 bool mathed_parse_macro(string & name, LyXLex & lex)
1087 return parser.parse_macro(name);
1092 bool mathed_parse_normal(MathAtom & t, string const & str)
1094 istringstream is(str.c_str());
1096 return parser.parse_normal(t);
1099 bool mathed_parse_normal(MathAtom & t, istream & is)
1102 return parser.parse_normal(t);
1105 bool mathed_parse_normal(MathAtom & t, LyXLex & lex)
1108 return parser.parse_normal(t);