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"
57 #include "math_inset.h"
58 #include "math_arrayinset.h"
59 #include "math_braceinset.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_matrixinset.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"
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;
201 string Token::asString() const
203 return cs_.size() ? cs_ : string(1, char_);
206 bool operator==(Token const & s, Token const & t)
208 return s.character() == t.character()
209 && s.cat() == t.cat() && s.cs() == t.cs();
212 bool operator!=(Token const & s, Token const & t)
217 ostream & operator<<(ostream & os, Token const & t)
220 os << "\\" << t.cs();
222 os << "[" << t.character() << "," << t.cat() << "]";
231 Parser(LyXLex & lex);
233 Parser(istream & is);
236 string parse_macro();
238 bool parse_normal(MathAtom &);
240 void parse_into(MathArray & array, unsigned flags, MathTextCodes = LM_TC_MIN);
242 int lineno() const { return lineno_; }
248 string getArg(char lf, char rf);
252 void error(string const & msg);
254 bool parse_lines(MathAtom & t, bool numbered, bool outmost);
258 void tokenize(istream & is);
260 void tokenize(string const & s);
262 void push_back(Token const & t);
266 Token const & prevToken() const;
268 Token const & nextToken() const;
270 Token const & getToken();
272 void lex(string const & s);
279 std::vector<Token> tokens_;
291 Parser::Parser(LyXLex & lexer)
292 : lineno_(lexer.getLineNo()), pos_(0), curr_num_(false)
294 tokenize(lexer.getStream());
299 Parser::Parser(istream & is)
300 : lineno_(0), pos_(0), curr_num_(false)
306 void Parser::push_back(Token const & t)
308 tokens_.push_back(t);
312 void Parser::pop_back()
318 Token const & Parser::prevToken() const
320 static const Token dummy;
321 return pos_ > 0 ? tokens_[pos_ - 1] : dummy;
325 Token const & Parser::nextToken() const
327 static const Token dummy;
328 return good() ? tokens_[pos_] : dummy;
332 Token const & Parser::getToken()
334 static const Token dummy;
335 return good() ? tokens_[pos_++] : dummy;
339 void Parser::putback()
345 bool Parser::good() const
347 return pos_ < tokens_.size();
351 char Parser::getChar()
354 lyxerr << "The input stream is not well..." << endl;
355 return tokens_[pos_++].character();
359 string Parser::getArg(char lf, char rg)
367 while ((c = getChar()) != rg && good())
374 void Parser::tokenize(istream & is)
376 // eat everything up to the next \end_inset or end of stream
377 // and store it in s for further tokenization
382 if (s.size() >= 10 && s.substr(s.size() - 10) == "\\end_inset") {
383 s = s.substr(0, s.size() - 10);
393 void Parser::tokenize(string const & buffer)
395 static bool init_done = false;
402 istringstream is(buffer.c_str(), ios::in | ios::binary);
407 switch (catcode(c)) {
411 if (catcode(c) == catNewline)
412 ; //push_back(Token("par"));
414 push_back(Token(' ', catSpace));
421 while (is.get(c) && catcode(c) != catNewline)
430 if (catcode(c) == catLetter) {
431 while (is.get(c) && catcode(c) == catLetter)
433 if (catcode(c) == catSpace)
434 while (is.get(c) && catcode(c) == catSpace)
443 push_back(Token(c, catcode(c)));
448 lyxerr << "\nTokens: ";
449 for (unsigned i = 0; i < tokens_.size(); ++i)
450 lyxerr << tokens_[i];
456 void Parser::error(string const & msg)
458 lyxerr << "Line ~" << lineno_ << ": Math parse error: " << msg << endl;
463 bool Parser::parse_lines(MathAtom & t, bool numbered, bool outmost)
465 MathGridInset * p = t->asGridInset();
467 lyxerr << "error in Parser::parse_lines() 1\n";
471 const int cols = p->ncols();
473 // save global variables
474 bool const saved_num = curr_num_;
475 string const saved_label = curr_label_;
477 for (int row = 0; true; ++row) {
478 // reset global variables
479 curr_num_ = numbered;
483 for (int col = 0; col < cols; ++col) {
484 //lyxerr << "reading cell " << row << " " << col << "\n";
485 parse_into(p->cell(col + row * cols), FLAG_BLOCK);
488 if (prevToken().cat() != catAlign) {
489 //lyxerr << "less cells read than normal in row/col: "
490 // << row << " " << col << "\n";
496 MathMatrixInset * m = t->asMatrixInset();
498 lyxerr << "error in Parser::parse_lines() 2\n";
501 m->numbered(row, curr_num_);
502 m->label(row, curr_label_);
503 if (curr_skip_.size()) {
504 m->vskip(LyXLength(curr_skip_), row);
510 if (prevToken() != Token("\\")) {
511 //lyxerr << "no newline here\n";
518 // restore "global" variables
519 curr_num_ = saved_num;
520 curr_label_ = saved_label;
526 string Parser::parse_macro()
528 string name = "{error}";
530 while (nextToken().cat() == catSpace)
533 if (getToken().cs() != "newcommand") {
534 lyxerr << "\\newcommand expected\n";
538 if (getToken().cat() != catBegin) {
539 lyxerr << "'{' in \\newcommand expected (1)\n";
543 name = getToken().cs();
545 if (getToken().cat() != catEnd) {
546 lyxerr << "'}' expected\n";
550 string arg = getArg('[', ']');
551 int narg = arg.empty() ? 0 : atoi(arg.c_str());
553 if (getToken().cat() != catBegin) {
554 lyxerr << "'{' in \\newcommand expected (2)\n";
559 parse_into(ar, FLAG_BRACE_LAST);
560 MathMacroTable::create(name, narg, ar);
565 bool Parser::parse_normal(MathAtom & matrix)
567 while (nextToken().cat() == catSpace)
570 Token const & t = getToken();
573 matrix = MathAtom(new MathMatrixInset(LM_OT_SIMPLE));
574 parse_into(matrix->cell(0), 0);
578 if (t.cat() == catMath) {
579 Token const & n = getToken();
580 if (n.cat() == catMath) {
581 // TeX's $$...$$ syntax for displayed math
582 matrix = MathAtom(new MathMatrixInset(LM_OT_EQUATION));
583 MathMatrixInset * p = matrix->asMatrixInset();
584 parse_into(p->cell(0), 0);
585 p->numbered(0, curr_num_);
586 p->label(0, curr_label_);
588 // simple $...$ stuff
590 matrix = MathAtom(new MathMatrixInset(LM_OT_SIMPLE));
591 parse_into(matrix->cell(0), 0);
596 if (!t.cs().size()) {
597 lyxerr << "start of math expected, got '" << t << "'\n";
601 string const & cs = t.cs();
606 matrix = MathAtom(new MathMatrixInset(LM_OT_EQUATION));
607 MathMatrixInset * p = matrix->asMatrixInset();
608 parse_into(p->cell(0), 0);
609 p->numbered(0, curr_num_);
610 p->label(0, curr_label_);
615 lyxerr << "'begin' of un-simple math expected, got '" << cs << "'\n";
619 string const name = getArg('{', '}');
621 if (name == "equation" || name == "equation*" || name == "displaymath") {
622 curr_num_ = (name == "equation");
624 matrix = MathAtom(new MathMatrixInset(LM_OT_EQUATION));
625 MathMatrixInset * p = matrix->asMatrixInset();
626 parse_into(p->cell(0), FLAG_END);
627 p->numbered(0, curr_num_);
628 p->label(0, curr_label_);
632 if (name == "eqnarray" || name == "eqnarray*") {
633 matrix = MathAtom(new MathMatrixInset(LM_OT_EQNARRAY));
634 return parse_lines(matrix, !stared(name), true);
637 if (name == "align" || name == "align*") {
638 matrix = MathAtom(new MathMatrixInset(LM_OT_ALIGN));
639 return parse_lines(matrix, !stared(name), true);
642 if (name == "alignat" || name == "alignat*") {
643 int nc = 2 * atoi(getArg('{', '}').c_str());
644 matrix = MathAtom(new MathMatrixInset(LM_OT_ALIGNAT, nc));
645 return parse_lines(matrix, !stared(name), true);
648 if (name == "xalignat" || name == "xalignat*") {
649 int nc = 2 * atoi(getArg('{', '}').c_str());
650 matrix = MathAtom(new MathMatrixInset(LM_OT_XALIGNAT, nc));
651 return parse_lines(matrix, !stared(name), true);
654 if (name == "xxalignat") {
655 int nc = 2 * atoi(getArg('{', '}').c_str());
656 matrix = MathAtom(new MathMatrixInset(LM_OT_XXALIGNAT, nc));
657 return parse_lines(matrix, !stared(name), true);
660 if (name == "multline" || name == "multline*") {
661 matrix = MathAtom(new MathMatrixInset(LM_OT_MULTLINE));
662 return parse_lines(matrix, !stared(name), true);
665 if (name == "gather" || name == "gather*") {
666 matrix = MathAtom(new MathMatrixInset(LM_OT_GATHER));
667 return parse_lines(matrix, !stared(name), true);
670 lyxerr[Debug::MATHED] << "1: unknown math environment: " << name << "\n";
675 void Parser::parse_into(MathArray & array, unsigned flags, MathTextCodes code)
681 Token const & t = getToken();
683 //lyxerr << "t: " << t << " flags: " << flags << "'\n";
684 //array.dump(lyxerr);
687 if (flags & FLAG_ITEM) {
689 if (t.cat() == catBegin) {
690 // skip the brace and collect everything to the next matching
692 flags |= FLAG_BRACE_LAST;
695 // handle only this single token, leave the loop if done
700 if (flags & FLAG_BLOCK) {
701 if (t.cat() == catAlign || t.cs() == "\\")
703 if (t.cs() == "end") {
712 if (t.cat() == catMath)
715 else if (t.cat() == catLetter)
716 add(array, t.character(), code);
718 else if (t.cat() == catSpace && code == LM_TC_TEXTRM)
719 add(array, t.character(), code);
721 else if (t.cat() == catParameter) {
722 Token const & n = getToken();
723 array.push_back(MathAtom(new MathMacroArgument(n.character() - '0')));
726 else if (t.cat() == catBegin) {
728 parse_into(ar, FLAG_BRACE_LAST);
729 #ifndef WITH_WARNINGS
730 #warning this might be wrong in general!
732 // ignore braces around simple items
733 if (ar.size() == 1 || (ar.size() == 2 && ar.back()->asScriptInset())) {
736 array.push_back(MathAtom(new MathBraceInset));
737 array.back()->cell(0).swap(ar);
741 else if (t.cat() == catEnd) {
742 if (flags & FLAG_BRACE_LAST)
744 //lyxerr << "found '}' unexpectedly, array: '" << array << "'\n";
745 lyxerr << "found '}' unexpectedly\n";
746 add(array, '}', LM_TC_TEX);
749 else if (t.cat() == catAlign) {
750 //lyxerr << "found tab unexpectedly, array: '" << array << "'\n";
751 lyxerr << "found tab unexpectedly\n";
752 add(array, '&', LM_TC_TEX);
755 else if (t.cat() == catSuper || t.cat() == catSub) {
756 bool up = (t.cat() == catSuper);
757 MathScriptInset * p = 0;
759 p = array.back()->asScriptInset();
760 if (!p || p->has(up)) {
761 array.push_back(MathAtom(new MathScriptInset(up)));
762 p = array.back()->asScriptInset();
765 parse_into(p->cell(up), FLAG_ITEM);
770 else if (t.character() == ']' && (flags & FLAG_BRACK_END))
773 else if (t.cat() == catOther)
774 add(array, t.character(), code);
779 else if (t.cs() == "protect")
780 // ignore \\protect, will be re-added during output
783 else if (t.cs() == "end")
786 else if (t.cs() == ")")
789 else if (t.cs() == "]")
792 else if (t.cs() == "\\") {
793 curr_skip_ = getArg('[', ']');
794 //lyxerr << "found newline unexpectedly, array: '" << array << "'\n";
795 lyxerr << "found newline unexpectedly\n";
796 array.push_back(createMathInset("\\"));
799 else if (t.cs() == "limits")
802 else if (t.cs() == "nolimits")
805 else if (t.cs() == "nonumber")
808 else if (t.cs() == "number")
811 else if (t.cs() == "sqrt") {
814 array.push_back(MathAtom(new MathRootInset));
815 parse_into(array.back()->cell(0), FLAG_BRACK_END);
816 parse_into(array.back()->cell(1), FLAG_ITEM);
819 array.push_back(MathAtom(new MathSqrtInset));
820 parse_into(array.back()->cell(0), FLAG_ITEM);
824 else if (t.cs() == "left") {
825 string l = getToken().asString();
827 parse_into(ar, FLAG_RIGHT);
828 string r = getToken().asString();
829 MathAtom dl(new MathDelimInset(l, r));
834 else if (t.cs() == "right") {
835 if (!(flags & FLAG_RIGHT)) {
836 //lyxerr << "got so far: '" << array << "'\n";
837 error("Unmatched right delimiter");
845 lyxerr[Debug::MATHED] << "LM_TK_STY not implemented\n";
846 //MathArray tmp = array;
847 //MathSizeInset * p = new MathSizeInset(MathStyles(lval_->id));
848 //array.push_back(p);
849 //parse_into(p->cell(0), FLAG_BRACE_FONT);
855 else if (t.cs() == "begin") {
856 string const name = getArg('{', '}');
857 if (name == "array") {
858 string const valign = getArg('[', ']') + 'c';
859 string const halign = getArg('{', '}');
861 MathAtom(new MathArrayInset(halign.size(), 1, valign[0], halign)));
862 parse_lines(array.back(), false, false);
863 } else if (name == "split") {
864 array.push_back(MathAtom(new MathSplitInset(1)));
865 parse_lines(array.back(), false, false);
867 lyxerr[Debug::MATHED] << "unknow math inset begin '" << name << "'\n";
870 else if (t.cs() == "kern") {
876 Token const & t = getToken();
882 if (isValidLength(s))
885 array.push_back(MathAtom(new MathKernInset(s)));
888 else if (t.cs() == "label") {
889 curr_label_ = getArg('{', '}');
892 else if (t.cs() == "choose" || t.cs() == "over" || t.cs() == "atop") {
893 MathAtom p = createMathInset(t.cs());
894 array.swap(p->cell(0));
895 parse_into(p->cell(1), flags, code);
902 else if (t.cs() == "mbox") {
903 array.push_back(createMathInset(t.cs()));
904 // slurp in the argument of mbox
906 MathBoxInset * p = array.back()->asBoxInset();
911 else if (t.cs().size()) {
912 latexkeys const * l = in_word_set(t.cs());
914 if (l->token == LM_TK_FONT) {
915 //lyxerr << "starting font\n";
916 //CatCode catSpaceSave = theCatcode[' '];
917 //if (l->id == LM_TC_TEXTRM) {
918 // // temporarily change catcode
919 // theCatcode[' '] = catLetter;
923 parse_into(ar, FLAG_ITEM, static_cast<MathTextCodes>(l->id));
926 // undo catcode changes
927 ////theCatcode[' '] = catSpaceSave;
928 //lyxerr << "ending font\n";
931 else if (l->token == LM_TK_OLDFONT) {
932 code = static_cast<MathTextCodes>(l->id);
936 MathAtom p = createMathInset(t.cs());
937 for (MathInset::idx_type i = 0; i < p->nargs(); ++i)
938 parse_into(p->cell(i), FLAG_ITEM);
944 MathAtom p = createMathInset(t.cs());
945 for (MathInset::idx_type i = 0; i < p->nargs(); ++i)
946 parse_into(p->cell(i), FLAG_ITEM);
952 if (flags & FLAG_LEAVE) {
953 flags &= ~FLAG_LEAVE;
959 lyxerr << " Math Panic, expect problems!\n";
960 // Search for the end command.
964 } while (good() && t.cs() != "end");
970 } // anonymous namespace
973 void mathed_parse_cell(MathArray & ar, string const & str)
975 istringstream is(str.c_str());
976 mathed_parse_cell(ar, is);
980 void mathed_parse_cell(MathArray & ar, istream & is)
982 Parser(is).parse_into(ar, 0);
987 string mathed_parse_macro(string const & str)
989 istringstream is(str.c_str());
991 return parser.parse_macro();
994 string mathed_parse_macro(istream & is)
997 return parser.parse_macro();
1000 string mathed_parse_macro(LyXLex & lex)
1003 return parser.parse_macro();
1008 bool mathed_parse_normal(MathAtom & t, string const & str)
1010 istringstream is(str.c_str());
1012 return parser.parse_normal(t);
1015 bool mathed_parse_normal(MathAtom & t, istream & is)
1018 return parser.parse_normal(t);
1021 bool mathed_parse_normal(MathAtom & t, LyXLex & lex)
1024 return parser.parse_normal(t);