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}
52 #pragma implementation
55 #include "math_parser.h"
56 #include "math_inset.h"
57 #include "math_arrayinset.h"
58 #include "math_braceinset.h"
59 #include "math_casesinset.h"
60 #include "math_charinset.h"
61 #include "math_deliminset.h"
62 #include "math_factory.h"
63 #include "math_funcinset.h"
64 #include "math_kerninset.h"
65 #include "math_macro.h"
66 #include "math_macrotable.h"
67 #include "math_macrotemplate.h"
68 #include "math_hullinset.h"
69 #include "math_rootinset.h"
70 #include "math_sqrtinset.h"
71 #include "math_scriptinset.h"
72 #include "math_specialcharinset.h"
73 #include "math_splitinset.h"
74 #include "math_sqrtinset.h"
75 #include "math_support.h"
78 #include "support/lstrings.h"
89 bool stared(string const & s)
91 unsigned n = s.size();
92 return n && s[n - 1] == '*';
96 void add(MathArray & ar, char c, MathTextCodes code)
98 ar.push_back(MathAtom(new MathCharInset(c, code)));
102 // These are TeX's catcodes
104 catEscape, // 0 backslash
114 catSpace, // 10 space
115 catLetter, // 11 a-zA-Z
116 catOther, // 12 none of the above
119 catInvalid // 15 <delete>
122 CatCode theCatcode[256];
125 inline CatCode catcode(unsigned char c)
127 return theCatcode[c];
132 FLAG_BRACE_LAST = 1 << 1, // last closing brace ends the parsing process
133 FLAG_RIGHT = 1 << 2, // next \\right ends the parsing process
134 FLAG_END = 1 << 3, // next \\end ends the parsing process
135 FLAG_BRACK_END = 1 << 4, // next closing bracket ends the parsing process
136 FLAG_ITEM = 1 << 7, // read a (possibly braced token)
137 FLAG_BLOCK = 1 << 8, // next block ends the parsing process
138 FLAG_LEAVE = 1 << 9 // leave the loop at the end
144 for (int i = 0; i <= 255; ++i)
145 theCatcode[i] = catOther;
146 for (int i = 'a'; i <= 'z'; ++i)
147 theCatcode[i] = catLetter;
148 for (int i = 'A'; i <= 'Z'; ++i)
149 theCatcode[i] = catLetter;
151 theCatcode['\\'] = catEscape;
152 theCatcode['{'] = catBegin;
153 theCatcode['}'] = catEnd;
154 theCatcode['$'] = catMath;
155 theCatcode['&'] = catAlign;
156 theCatcode['\n'] = catNewline;
157 theCatcode['#'] = catParameter;
158 theCatcode['^'] = catSuper;
159 theCatcode['_'] = catSub;
160 theCatcode['
\7f'] = catIgnore;
161 theCatcode[' '] = catSpace;
162 theCatcode['\t'] = catSpace;
163 theCatcode['\r'] = catSpace;
164 theCatcode['~'] = catActive;
165 theCatcode['%'] = catComment;
171 // Helper class for parsing
177 Token() : cs_(), char_(0), cat_(catIgnore) {}
179 Token(char c, CatCode cat) : cs_(), char_(c), cat_(cat) {}
181 Token(const string & cs) : cs_(cs), char_(0), cat_(catIgnore) {}
184 string const & cs() const { return cs_; }
186 CatCode cat() const { return cat_; }
188 char character() const { return char_; }
190 string asString() const;
203 bool Token::isCR() const
205 return cs_ == "\\" || cs_ == "cr" || cs_ == "crcr";
208 string Token::asString() const
210 return cs_.size() ? cs_ : string(1, char_);
213 bool operator==(Token const & s, Token const & t)
215 return s.character() == t.character()
216 && s.cat() == t.cat() && s.cs() == t.cs();
219 bool operator!=(Token const & s, Token const & t)
224 ostream & operator<<(ostream & os, Token const & t)
227 os << "\\" << t.cs();
229 os << "[" << t.character() << "," << t.cat() << "]";
238 Parser(LyXLex & lex);
240 Parser(istream & is);
243 string parse_macro();
245 bool parse_normal(MathAtom &);
247 void parse_into(MathArray & array, unsigned flags, MathTextCodes = LM_TC_MIN);
249 int lineno() const { return lineno_; }
255 string getArg(char lf, char rf);
259 void error(string const & msg);
261 bool parse_lines(MathAtom & t, bool numbered, bool outmost);
265 void tokenize(istream & is);
267 void tokenize(string const & s);
269 void push_back(Token const & t);
273 Token const & prevToken() const;
275 Token const & nextToken() const;
277 Token const & getToken();
279 void lex(string const & s);
286 std::vector<Token> tokens_;
298 Parser::Parser(LyXLex & lexer)
299 : lineno_(lexer.getLineNo()), pos_(0), curr_num_(false)
301 tokenize(lexer.getStream());
306 Parser::Parser(istream & is)
307 : lineno_(0), pos_(0), curr_num_(false)
313 void Parser::push_back(Token const & t)
315 tokens_.push_back(t);
319 void Parser::pop_back()
325 Token const & Parser::prevToken() const
327 static const Token dummy;
328 return pos_ > 0 ? tokens_[pos_ - 1] : dummy;
332 Token const & Parser::nextToken() const
334 static const Token dummy;
335 return good() ? tokens_[pos_] : dummy;
339 Token const & Parser::getToken()
341 static const Token dummy;
342 return good() ? tokens_[pos_++] : dummy;
346 void Parser::putback()
352 bool Parser::good() const
354 return pos_ < tokens_.size();
358 char Parser::getChar()
361 lyxerr << "The input stream is not well..." << endl;
362 return tokens_[pos_++].character();
366 string Parser::getArg(char lf, char rg)
374 while ((c = getChar()) != rg && good())
381 void Parser::tokenize(istream & is)
383 // eat everything up to the next \end_inset or end of stream
384 // and store it in s for further tokenization
389 if (s.size() >= 10 && s.substr(s.size() - 10) == "\\end_inset") {
390 s = s.substr(0, s.size() - 10);
400 void Parser::tokenize(string const & buffer)
402 static bool init_done = false;
409 istringstream is(buffer.c_str(), ios::in | ios::binary);
414 switch (catcode(c)) {
418 if (catcode(c) == catNewline)
419 ; //push_back(Token("par"));
421 push_back(Token(' ', catSpace));
428 while (is.get(c) && catcode(c) != catNewline)
437 if (catcode(c) == catLetter) {
438 while (is.get(c) && catcode(c) == catLetter)
440 if (catcode(c) == catSpace)
441 while (is.get(c) && catcode(c) == catSpace)
450 push_back(Token(c, catcode(c)));
455 lyxerr << "\nTokens: ";
456 for (unsigned i = 0; i < tokens_.size(); ++i)
457 lyxerr << tokens_[i];
463 void Parser::error(string const & msg)
465 lyxerr << "Line ~" << lineno_ << ": Math parse error: " << msg << endl;
470 bool Parser::parse_lines(MathAtom & t, bool numbered, bool outmost)
472 MathGridInset * p = t->asGridInset();
474 lyxerr << "error in Parser::parse_lines() 1\n";
478 const int cols = p->ncols();
480 // save global variables
481 bool const saved_num = curr_num_;
482 string const saved_label = curr_label_;
484 for (int row = 0; true; ++row) {
485 // reset global variables
486 curr_num_ = numbered;
490 for (int col = 0; col < cols; ++col) {
491 //lyxerr << "reading cell " << row << " " << col << "\n";
492 parse_into(p->cell(col + row * cols), FLAG_BLOCK);
495 if (prevToken().cat() != catAlign) {
496 //lyxerr << "less cells read than normal in row/col: "
497 // << row << " " << col << "\n";
503 MathHullInset * m = t->asHullInset();
505 lyxerr << "error in Parser::parse_lines() 2\n";
508 m->numbered(row, curr_num_);
509 m->label(row, curr_label_);
510 if (curr_skip_.size()) {
511 m->vskip(LyXLength(curr_skip_), row);
517 if (!prevToken().isCR()) {
518 //lyxerr << "no newline here\n";
525 // restore "global" variables
526 curr_num_ = saved_num;
527 curr_label_ = saved_label;
533 string Parser::parse_macro()
535 string name = "{error}";
537 while (nextToken().cat() == catSpace)
540 if (getToken().cs() != "newcommand") {
541 lyxerr << "\\newcommand expected\n";
545 if (getToken().cat() != catBegin) {
546 lyxerr << "'{' in \\newcommand expected (1)\n";
550 name = getToken().cs();
552 if (getToken().cat() != catEnd) {
553 lyxerr << "'}' expected\n";
557 string arg = getArg('[', ']');
558 int narg = arg.empty() ? 0 : atoi(arg.c_str());
560 if (getToken().cat() != catBegin) {
561 lyxerr << "'{' in \\newcommand expected (2)\n";
566 parse_into(ar, FLAG_BRACE_LAST);
567 MathMacroTable::create(name, narg, ar);
572 bool Parser::parse_normal(MathAtom & matrix)
574 while (nextToken().cat() == catSpace)
577 Token const & t = getToken();
580 matrix = MathAtom(new MathHullInset(LM_OT_SIMPLE));
581 parse_into(matrix->cell(0), 0);
585 if (t.cat() == catMath) {
586 Token const & n = getToken();
587 if (n.cat() == catMath) {
588 // TeX's $$...$$ syntax for displayed math
589 matrix = MathAtom(new MathHullInset(LM_OT_EQUATION));
590 MathHullInset * p = matrix->asHullInset();
591 parse_into(p->cell(0), 0);
592 p->numbered(0, curr_num_);
593 p->label(0, curr_label_);
595 // simple $...$ stuff
597 matrix = MathAtom(new MathHullInset(LM_OT_SIMPLE));
598 parse_into(matrix->cell(0), 0);
603 if (!t.cs().size()) {
604 lyxerr << "start of math expected, got '" << t << "'\n";
608 string const & cs = t.cs();
613 matrix = MathAtom(new MathHullInset(LM_OT_EQUATION));
614 MathHullInset * p = matrix->asHullInset();
615 parse_into(p->cell(0), 0);
616 p->numbered(0, curr_num_);
617 p->label(0, curr_label_);
622 lyxerr << "'begin' of un-simple math expected, got '" << cs << "'\n";
626 string const name = getArg('{', '}');
628 if (name == "equation" || name == "equation*" || name == "displaymath") {
629 curr_num_ = (name == "equation");
631 matrix = MathAtom(new MathHullInset(LM_OT_EQUATION));
632 MathHullInset * p = matrix->asHullInset();
633 parse_into(p->cell(0), FLAG_END);
634 p->numbered(0, curr_num_);
635 p->label(0, curr_label_);
639 if (name == "eqnarray" || name == "eqnarray*") {
640 matrix = MathAtom(new MathHullInset(LM_OT_EQNARRAY));
641 return parse_lines(matrix, !stared(name), true);
644 if (name == "align" || name == "align*") {
645 matrix = MathAtom(new MathHullInset(LM_OT_ALIGN));
646 return parse_lines(matrix, !stared(name), true);
649 if (name == "alignat" || name == "alignat*") {
650 int nc = 2 * atoi(getArg('{', '}').c_str());
651 matrix = MathAtom(new MathHullInset(LM_OT_ALIGNAT, nc));
652 return parse_lines(matrix, !stared(name), true);
655 if (name == "xalignat" || name == "xalignat*") {
656 int nc = 2 * atoi(getArg('{', '}').c_str());
657 matrix = MathAtom(new MathHullInset(LM_OT_XALIGNAT, nc));
658 return parse_lines(matrix, !stared(name), true);
661 if (name == "xxalignat") {
662 int nc = 2 * atoi(getArg('{', '}').c_str());
663 matrix = MathAtom(new MathHullInset(LM_OT_XXALIGNAT, nc));
664 return parse_lines(matrix, !stared(name), true);
667 if (name == "multline" || name == "multline*") {
668 matrix = MathAtom(new MathHullInset(LM_OT_MULTLINE));
669 return parse_lines(matrix, !stared(name), true);
672 if (name == "gather" || name == "gather*") {
673 matrix = MathAtom(new MathHullInset(LM_OT_GATHER));
674 return parse_lines(matrix, !stared(name), true);
677 lyxerr[Debug::MATHED] << "1: unknown math environment: " << name << "\n";
678 lyxerr << "1: unknown math environment: " << name << "\n";
683 void Parser::parse_into(MathArray & array, unsigned flags, MathTextCodes code)
689 Token const & t = getToken();
691 //lyxerr << "t: " << t << " flags: " << flags << "'\n";
692 //array.dump(lyxerr);
695 if (flags & FLAG_ITEM) {
697 if (t.cat() == catBegin) {
698 // skip the brace and collect everything to the next matching
700 flags |= FLAG_BRACE_LAST;
703 // handle only this single token, leave the loop if done
708 if (flags & FLAG_BLOCK) {
709 if (t.cat() == catAlign || t.isCR())
711 if (t.cs() == "end") {
720 if (t.cat() == catMath)
723 else if (t.cat() == catLetter)
724 add(array, t.character(), code);
726 else if (t.cat() == catSpace && code == LM_TC_TEXTRM)
727 add(array, t.character(), code);
729 else if (t.cat() == catParameter) {
730 Token const & n = getToken();
731 array.push_back(MathAtom(new MathMacroArgument(n.character() - '0')));
734 else if (t.cat() == catBegin) {
736 parse_into(ar, FLAG_BRACE_LAST);
737 #ifndef WITH_WARNINGS
738 #warning this might be wrong in general!
740 // ignore braces around simple items
741 if (ar.size() == 1 || (ar.size() == 2 && ar.back()->asScriptInset())) {
744 array.push_back(MathAtom(new MathBraceInset));
745 array.back()->cell(0).swap(ar);
749 else if (t.cat() == catEnd) {
750 if (flags & FLAG_BRACE_LAST)
752 //lyxerr << "found '}' unexpectedly, array: '" << array << "'\n";
753 lyxerr << "found '}' unexpectedly\n";
754 add(array, '}', LM_TC_TEX);
757 else if (t.cat() == catAlign) {
758 //lyxerr << "found tab unexpectedly, array: '" << array << "'\n";
759 lyxerr << "found tab unexpectedly\n";
760 add(array, '&', LM_TC_TEX);
763 else if (t.cat() == catSuper || t.cat() == catSub) {
764 bool up = (t.cat() == catSuper);
765 MathScriptInset * p = 0;
767 p = array.back()->asScriptInset();
768 if (!p || p->has(up)) {
769 array.push_back(MathAtom(new MathScriptInset(up)));
770 p = array.back()->asScriptInset();
773 parse_into(p->cell(up), FLAG_ITEM);
778 else if (t.character() == ']' && (flags & FLAG_BRACK_END))
781 else if (t.cat() == catOther)
782 add(array, t.character(), code);
787 else if (t.cs() == "protect")
788 // ignore \\protect, will be re-added during output
791 else if (t.cs() == "end")
794 else if (t.cs() == ")")
797 else if (t.cs() == "]")
800 else if (t.cs() == "\\") {
801 curr_skip_ = getArg('[', ']');
802 //lyxerr << "found newline unexpectedly, array: '" << array << "'\n";
803 lyxerr << "found newline unexpectedly\n";
804 array.push_back(createMathInset("\\"));
807 else if (t.cs() == "limits")
810 else if (t.cs() == "nolimits")
813 else if (t.cs() == "nonumber")
816 else if (t.cs() == "number")
819 else if (t.cs() == "sqrt") {
822 array.push_back(MathAtom(new MathRootInset));
823 parse_into(array.back()->cell(0), FLAG_BRACK_END);
824 parse_into(array.back()->cell(1), FLAG_ITEM);
827 array.push_back(MathAtom(new MathSqrtInset));
828 parse_into(array.back()->cell(0), FLAG_ITEM);
832 else if (t.cs() == "left") {
833 string l = getToken().asString();
835 parse_into(ar, FLAG_RIGHT);
836 string r = getToken().asString();
837 MathAtom dl(new MathDelimInset(l, r));
842 else if (t.cs() == "right") {
843 if (!(flags & FLAG_RIGHT)) {
844 //lyxerr << "got so far: '" << array << "'\n";
845 error("Unmatched right delimiter");
853 lyxerr[Debug::MATHED] << "LM_TK_STY not implemented\n";
854 //MathArray tmp = array;
855 //MathSizeInset * p = new MathSizeInset(MathStyles(lval_->id));
856 //array.push_back(p);
857 //parse_into(p->cell(0), FLAG_BRACE_FONT);
863 else if (t.cs() == "begin") {
864 string const name = getArg('{', '}');
865 if (name == "array") {
866 string const valign = getArg('[', ']') + 'c';
867 string const halign = getArg('{', '}');
869 MathAtom(new MathArrayInset(halign.size(), 1, valign[0], halign)));
870 parse_lines(array.back(), false, false);
871 } else if (name == "split") {
872 array.push_back(MathAtom(new MathSplitInset(1)));
873 parse_lines(array.back(), false, false);
874 } else if (name == "cases") {
875 array.push_back(MathAtom(new MathCasesInset));
876 parse_lines(array.back(), false, false);
878 lyxerr << "unknow math inset begin '" << name << "'\n";
881 else if (t.cs() == "kern") {
887 Token const & t = getToken();
893 if (isValidLength(s))
896 array.push_back(MathAtom(new MathKernInset(s)));
899 else if (t.cs() == "label") {
900 curr_label_ = getArg('{', '}');
903 else if (t.cs() == "choose" || t.cs() == "over" || t.cs() == "atop") {
904 MathAtom p = createMathInset(t.cs());
905 array.swap(p->cell(0));
906 parse_into(p->cell(1), flags, code);
913 else if (t.cs() == "mbox") {
914 array.push_back(createMathInset(t.cs()));
915 // slurp in the argument of mbox
917 MathBoxInset * p = array.back()->asBoxInset();
922 else if (t.cs().size()) {
923 latexkeys const * l = in_word_set(t.cs());
925 if (l->token == LM_TK_FONT) {
926 //lyxerr << "starting font\n";
927 //CatCode catSpaceSave = theCatcode[' '];
928 //if (l->id == LM_TC_TEXTRM) {
929 // // temporarily change catcode
930 // theCatcode[' '] = catLetter;
934 parse_into(ar, FLAG_ITEM, static_cast<MathTextCodes>(l->id));
937 // undo catcode changes
938 ////theCatcode[' '] = catSpaceSave;
939 //lyxerr << "ending font\n";
942 else if (l->token == LM_TK_OLDFONT) {
943 code = static_cast<MathTextCodes>(l->id);
947 MathAtom p = createMathInset(t.cs());
948 for (MathInset::idx_type i = 0; i < p->nargs(); ++i)
949 parse_into(p->cell(i), FLAG_ITEM);
955 MathAtom p = createMathInset(t.cs());
956 for (MathInset::idx_type i = 0; i < p->nargs(); ++i)
957 parse_into(p->cell(i), FLAG_ITEM);
963 if (flags & FLAG_LEAVE) {
964 flags &= ~FLAG_LEAVE;
970 lyxerr << " Math Panic, expect problems!\n";
971 // Search for the end command.
975 } while (good() && t.cs() != "end");
981 } // anonymous namespace
984 void mathed_parse_cell(MathArray & ar, string const & str)
986 istringstream is(str.c_str());
987 mathed_parse_cell(ar, is);
991 void mathed_parse_cell(MathArray & ar, istream & is)
993 Parser(is).parse_into(ar, 0);
998 string mathed_parse_macro(string const & str)
1000 istringstream is(str.c_str());
1002 return parser.parse_macro();
1005 string mathed_parse_macro(istream & is)
1008 return parser.parse_macro();
1011 string mathed_parse_macro(LyXLex & lex)
1014 return parser.parse_macro();
1019 bool mathed_parse_normal(MathAtom & t, string const & str)
1021 istringstream is(str.c_str());
1023 return parser.parse_normal(t);
1026 bool mathed_parse_normal(MathAtom & t, istream & is)
1029 return parser.parse_normal(t);
1032 bool mathed_parse_normal(MathAtom & t, LyXLex & lex)
1035 return parser.parse_normal(t);