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();
278 /// skips spaces if any
280 /// counts a sequence of hlines
283 void lex(string const & s);
290 std::vector<Token> tokens_;
302 Parser::Parser(LyXLex & lexer)
303 : lineno_(lexer.getLineNo()), pos_(0), curr_num_(false)
305 tokenize(lexer.getStream());
310 Parser::Parser(istream & is)
311 : lineno_(0), pos_(0), curr_num_(false)
317 void Parser::push_back(Token const & t)
319 tokens_.push_back(t);
323 void Parser::pop_back()
329 Token const & Parser::prevToken() const
331 static const Token dummy;
332 return pos_ > 0 ? tokens_[pos_ - 1] : dummy;
336 Token const & Parser::nextToken() const
338 static const Token dummy;
339 return good() ? tokens_[pos_] : dummy;
343 Token const & Parser::getToken()
345 static const Token dummy;
346 //lyxerr << "looking at token " << tokens_[pos_] << '\n';
347 return good() ? tokens_[pos_++] : dummy;
351 void Parser::skipSpaces()
353 while (nextToken().cat() == catSpace)
358 int Parser::readHLines()
362 while (nextToken().cs() == "hline") {
371 void Parser::putback()
377 bool Parser::good() const
379 return pos_ < tokens_.size();
383 char Parser::getChar()
386 lyxerr << "The input stream is not well..." << endl;
387 return tokens_[pos_++].character();
391 string Parser::getArg(char lf, char rg)
399 while ((c = getChar()) != rg && good())
406 void Parser::tokenize(istream & is)
408 // eat everything up to the next \end_inset or end of stream
409 // and store it in s for further tokenization
414 if (s.size() >= 10 && s.substr(s.size() - 10) == "\\end_inset") {
415 s = s.substr(0, s.size() - 10);
425 void Parser::tokenize(string const & buffer)
427 static bool init_done = false;
434 istringstream is(buffer.c_str(), ios::in | ios::binary);
439 switch (catcode(c)) {
443 if (catcode(c) == catNewline)
444 ; //push_back(Token("par"));
446 push_back(Token(' ', catSpace));
453 while (is.get(c) && catcode(c) != catNewline)
462 if (catcode(c) == catLetter) {
463 while (is.get(c) && catcode(c) == catLetter)
465 if (catcode(c) == catSpace)
466 while (is.get(c) && catcode(c) == catSpace)
475 push_back(Token(c, catcode(c)));
480 lyxerr << "\nTokens: ";
481 for (unsigned i = 0; i < tokens_.size(); ++i)
482 lyxerr << tokens_[i];
488 void Parser::error(string const & msg)
490 lyxerr << "Line ~" << lineno_ << ": Math parse error: " << msg << endl;
495 bool Parser::parse_lines(MathAtom & t, bool numbered, bool outmost)
497 MathGridInset * p = t->asGridInset();
499 lyxerr << "error in Parser::parse_lines() 1\n";
503 const int cols = p->ncols();
505 // save global variables
506 bool const saved_num = curr_num_;
507 string const saved_label = curr_label_;
509 // read initial hlines
510 p->rowinfo(0).lines_ = readHLines();
512 for (int row = 0; true; ++row) {
513 // reset global variables
514 curr_num_ = numbered;
518 for (int col = 0; col < cols; ++col) {
519 //lyxerr << "reading cell " << row << " " << col << "\n";
520 parse_into(p->cell(col + row * cols), FLAG_BLOCK);
522 // break if cell is not followed by an ampersand
523 if (nextToken().cat() != catAlign) {
524 //lyxerr << "less cells read than normal in row/col: "
525 // << row << " " << col << "\n";
529 // skip the ampersand
534 MathHullInset * m = t->asHullInset();
536 lyxerr << "error in Parser::parse_lines() 2\n";
539 m->numbered(row, curr_num_);
540 m->label(row, curr_label_);
541 if (curr_skip_.size()) {
542 m->vcrskip(LyXLength(curr_skip_), row);
548 if (nextToken().isCR()) {
552 // try to read a length
555 // read hlines for next row
556 p->rowinfo(row + 1).lines_ = readHLines();
559 // we are finished if the next token is an 'end'
560 if (nextToken().cs() == "end") {
561 // skip the end-token
565 // leave the 'read a line'-loop
569 // otherwise, we have to start a new row
573 // restore "global" variables
574 curr_num_ = saved_num;
575 curr_label_ = saved_label;
581 string Parser::parse_macro()
583 string name = "{error}";
586 if (getToken().cs() != "newcommand") {
587 lyxerr << "\\newcommand expected\n";
591 if (getToken().cat() != catBegin) {
592 lyxerr << "'{' in \\newcommand expected (1)\n";
596 name = getToken().cs();
598 if (getToken().cat() != catEnd) {
599 lyxerr << "'}' expected\n";
603 string arg = getArg('[', ']');
604 int narg = arg.empty() ? 0 : atoi(arg.c_str());
606 if (getToken().cat() != catBegin) {
607 lyxerr << "'{' in \\newcommand expected (2)\n";
612 parse_into(ar, FLAG_BRACE_LAST);
613 MathMacroTable::create(name, narg, ar);
618 bool Parser::parse_normal(MathAtom & matrix)
621 Token const & t = getToken();
624 matrix = MathAtom(new MathHullInset(LM_OT_SIMPLE));
625 parse_into(matrix->cell(0), 0);
629 if (t.cat() == catMath) {
630 Token const & n = getToken();
631 if (n.cat() == catMath) {
632 // TeX's $$...$$ syntax for displayed math
633 matrix = MathAtom(new MathHullInset(LM_OT_EQUATION));
634 MathHullInset * p = matrix->asHullInset();
635 parse_into(p->cell(0), 0);
636 p->numbered(0, curr_num_);
637 p->label(0, curr_label_);
639 // simple $...$ stuff
641 matrix = MathAtom(new MathHullInset(LM_OT_SIMPLE));
642 parse_into(matrix->cell(0), 0);
647 if (!t.cs().size()) {
648 lyxerr << "start of math expected, got '" << t << "'\n";
652 string const & cs = t.cs();
657 matrix = MathAtom(new MathHullInset(LM_OT_EQUATION));
658 MathHullInset * p = matrix->asHullInset();
659 parse_into(p->cell(0), 0);
660 p->numbered(0, curr_num_);
661 p->label(0, curr_label_);
666 lyxerr << "'begin' of un-simple math expected, got '" << cs << "'\n";
670 string const name = getArg('{', '}');
672 if (name == "equation" || name == "equation*" || name == "displaymath") {
673 curr_num_ = (name == "equation");
675 matrix = MathAtom(new MathHullInset(LM_OT_EQUATION));
676 MathHullInset * p = matrix->asHullInset();
677 parse_into(p->cell(0), FLAG_END);
678 p->numbered(0, curr_num_);
679 p->label(0, curr_label_);
683 if (name == "eqnarray" || name == "eqnarray*") {
684 matrix = MathAtom(new MathHullInset(LM_OT_EQNARRAY));
685 return parse_lines(matrix, !stared(name), true);
688 if (name == "align" || name == "align*") {
689 matrix = MathAtom(new MathHullInset(LM_OT_ALIGN));
690 return parse_lines(matrix, !stared(name), true);
693 if (name == "alignat" || name == "alignat*") {
694 int nc = 2 * atoi(getArg('{', '}').c_str());
695 matrix = MathAtom(new MathHullInset(LM_OT_ALIGNAT, nc));
696 return parse_lines(matrix, !stared(name), true);
699 if (name == "xalignat" || name == "xalignat*") {
700 int nc = 2 * atoi(getArg('{', '}').c_str());
701 matrix = MathAtom(new MathHullInset(LM_OT_XALIGNAT, nc));
702 return parse_lines(matrix, !stared(name), true);
705 if (name == "xxalignat") {
706 int nc = 2 * atoi(getArg('{', '}').c_str());
707 matrix = MathAtom(new MathHullInset(LM_OT_XXALIGNAT, nc));
708 return parse_lines(matrix, !stared(name), true);
711 if (name == "multline" || name == "multline*") {
712 matrix = MathAtom(new MathHullInset(LM_OT_MULTLINE));
713 return parse_lines(matrix, !stared(name), true);
716 if (name == "gather" || name == "gather*") {
717 matrix = MathAtom(new MathHullInset(LM_OT_GATHER));
718 return parse_lines(matrix, !stared(name), true);
721 lyxerr[Debug::MATHED] << "1: unknown math environment: " << name << "\n";
722 lyxerr << "1: unknown math environment: " << name << "\n";
727 void Parser::parse_into(MathArray & array, unsigned flags, MathTextCodes code)
733 Token const & t = getToken();
735 //lyxerr << "t: " << t << " flags: " << flags << "'\n";
736 //array.dump(lyxerr);
739 if (flags & FLAG_ITEM) {
741 if (t.cat() == catBegin) {
742 // skip the brace and collect everything to the next matching
744 flags |= FLAG_BRACE_LAST;
747 // handle only this single token, leave the loop if done
752 if (flags & FLAG_BLOCK) {
753 if (t.cat() == catAlign || t.isCR() || t.cs() == "end") {
762 if (t.cat() == catMath)
765 else if (t.cat() == catLetter)
766 add(array, t.character(), code);
768 else if (t.cat() == catSpace && code == LM_TC_TEXTRM)
769 add(array, t.character(), code);
771 else if (t.cat() == catParameter) {
772 Token const & n = getToken();
773 array.push_back(MathAtom(new MathMacroArgument(n.character() - '0')));
776 else if (t.cat() == catBegin) {
778 parse_into(ar, FLAG_BRACE_LAST);
779 #ifndef WITH_WARNINGS
780 #warning this might be wrong in general!
782 // ignore braces around simple items
783 if (ar.size() == 1 || (ar.size() == 2 && ar.back()->asScriptInset())) {
786 array.push_back(MathAtom(new MathBraceInset));
787 array.back()->cell(0).swap(ar);
791 else if (t.cat() == catEnd) {
792 if (flags & FLAG_BRACE_LAST)
794 lyxerr << "found '}' unexpectedly, array: '" << array << "'\n";
795 //lyxerr << "found '}' unexpectedly\n";
796 add(array, '}', LM_TC_TEX);
799 else if (t.cat() == catAlign) {
800 lyxerr << "found tab unexpectedly, array: '" << array << "'\n";
801 //lyxerr << "found tab unexpectedly\n";
802 add(array, '&', LM_TC_TEX);
805 else if (t.cat() == catSuper || t.cat() == catSub) {
806 bool up = (t.cat() == catSuper);
807 MathScriptInset * p = 0;
809 p = array.back()->asScriptInset();
810 if (!p || p->has(up)) {
811 array.push_back(MathAtom(new MathScriptInset(up)));
812 p = array.back()->asScriptInset();
815 parse_into(p->cell(up), FLAG_ITEM);
820 else if (t.character() == ']' && (flags & FLAG_BRACK_END))
823 else if (t.cat() == catOther)
824 add(array, t.character(), code);
829 else if (t.cs() == "protect")
830 // ignore \\protect, will be re-added during output
833 else if (t.cs() == "end")
836 else if (t.cs() == ")")
839 else if (t.cs() == "]")
842 else if (t.cs() == "\\") {
843 curr_skip_ = getArg('[', ']');
844 //lyxerr << "found newline unexpectedly, array: '" << array << "'\n";
845 lyxerr << "found newline unexpectedly\n";
846 array.push_back(createMathInset("\\"));
849 else if (t.cs() == "limits")
852 else if (t.cs() == "nolimits")
855 else if (t.cs() == "nonumber")
858 else if (t.cs() == "number")
861 else if (t.cs() == "sqrt") {
864 array.push_back(MathAtom(new MathRootInset));
865 parse_into(array.back()->cell(0), FLAG_BRACK_END);
866 parse_into(array.back()->cell(1), FLAG_ITEM);
869 array.push_back(MathAtom(new MathSqrtInset));
870 parse_into(array.back()->cell(0), FLAG_ITEM);
874 else if (t.cs() == "left") {
875 string l = getToken().asString();
877 parse_into(ar, FLAG_RIGHT);
878 string r = getToken().asString();
879 MathAtom dl(new MathDelimInset(l, r));
884 else if (t.cs() == "right") {
885 if (!(flags & FLAG_RIGHT)) {
886 //lyxerr << "got so far: '" << array << "'\n";
887 error("Unmatched right delimiter");
895 lyxerr[Debug::MATHED] << "LM_TK_STY not implemented\n";
896 //MathArray tmp = array;
897 //MathSizeInset * p = new MathSizeInset(MathStyles(lval_->id));
898 //array.push_back(p);
899 //parse_into(p->cell(0), FLAG_BRACE_FONT);
905 else if (t.cs() == "begin") {
906 string const name = getArg('{', '}');
907 if (name == "array") {
908 string const valign = getArg('[', ']') + 'c';
909 string const halign = getArg('{', '}');
910 array.push_back(MathAtom(new MathArrayInset(valign[0], halign)));
911 parse_lines(array.back(), false, false);
912 } else if (name == "split") {
913 array.push_back(MathAtom(new MathSplitInset(1)));
914 parse_lines(array.back(), false, false);
915 } else if (name == "cases") {
916 array.push_back(MathAtom(new MathCasesInset));
917 parse_lines(array.back(), false, false);
919 lyxerr << "unknow math inset begin '" << name << "'\n";
922 else if (t.cs() == "kern") {
928 Token const & t = getToken();
934 if (isValidLength(s))
937 array.push_back(MathAtom(new MathKernInset(s)));
940 else if (t.cs() == "label") {
941 curr_label_ = getArg('{', '}');
944 else if (t.cs() == "choose" || t.cs() == "over" || t.cs() == "atop") {
945 MathAtom p = createMathInset(t.cs());
946 array.swap(p->cell(0));
947 parse_into(p->cell(1), flags, code);
954 else if (t.cs() == "mbox") {
955 array.push_back(createMathInset(t.cs()));
956 // slurp in the argument of mbox
958 MathBoxInset * p = array.back()->asBoxInset();
963 else if (t.cs().size()) {
964 latexkeys const * l = in_word_set(t.cs());
966 if (l->token == LM_TK_FONT) {
967 //lyxerr << "starting font\n";
968 //CatCode catSpaceSave = theCatcode[' '];
969 //if (l->id == LM_TC_TEXTRM) {
970 // // temporarily change catcode
971 // theCatcode[' '] = catLetter;
975 parse_into(ar, FLAG_ITEM, static_cast<MathTextCodes>(l->id));
978 // undo catcode changes
979 ////theCatcode[' '] = catSpaceSave;
980 //lyxerr << "ending font\n";
983 else if (l->token == LM_TK_OLDFONT) {
984 code = static_cast<MathTextCodes>(l->id);
988 MathAtom p = createMathInset(t.cs());
989 for (MathInset::idx_type i = 0; i < p->nargs(); ++i)
990 parse_into(p->cell(i), FLAG_ITEM);
996 MathAtom p = createMathInset(t.cs());
997 for (MathInset::idx_type i = 0; i < p->nargs(); ++i)
998 parse_into(p->cell(i), FLAG_ITEM);
1004 if (flags & FLAG_LEAVE) {
1005 flags &= ~FLAG_LEAVE;
1011 lyxerr << " Math Panic, expect problems!\n";
1012 // Search for the end command.
1016 } while (good() && t.cs() != "end");
1022 } // anonymous namespace
1025 void mathed_parse_cell(MathArray & ar, string const & str)
1027 istringstream is(str.c_str());
1028 mathed_parse_cell(ar, is);
1032 void mathed_parse_cell(MathArray & ar, istream & is)
1034 Parser(is).parse_into(ar, 0);
1039 string mathed_parse_macro(string const & str)
1041 istringstream is(str.c_str());
1043 return parser.parse_macro();
1046 string mathed_parse_macro(istream & is)
1049 return parser.parse_macro();
1052 string mathed_parse_macro(LyXLex & lex)
1055 return parser.parse_macro();
1060 bool mathed_parse_normal(MathAtom & t, string const & str)
1062 istringstream is(str.c_str());
1064 return parser.parse_normal(t);
1067 bool mathed_parse_normal(MathAtom & t, istream & is)
1070 return parser.parse_normal(t);
1073 bool mathed_parse_normal(MathAtom & t, LyXLex & lex)
1076 return parser.parse_normal(t);