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] == '*';
66 // These are TeX's catcodes
68 catEscape, // 0 backslash
79 catLetter, // 11 a-zA-Z
80 catOther, // 12 none of the above
83 catInvalid // 15 <delete>
86 CatCode theCatcode[256];
89 inline CatCode catcode(unsigned char c)
96 FLAG_BRACE = 1 << 0, // an opening brace needed
97 FLAG_BRACE_LAST = 1 << 1, // last closing brace ends the parsing process
98 FLAG_RIGHT = 1 << 2, // next \\right ends the parsing process
99 FLAG_END = 1 << 3, // next \\end ends the parsing process
100 FLAG_BRACK_END = 1 << 4, // next closing bracket ends the parsing process
101 FLAG_NEWLINE = 1 << 6, // next \\\\ ends the parsing process
102 FLAG_ITEM = 1 << 7, // read a (possibly braced token)
103 FLAG_BLOCK = 1 << 8, // next block ends the parsing process
104 FLAG_LEAVE = 1 << 9 // leave the loop at the end
110 for (int i = 0; i <= 255; ++i)
111 theCatcode[i] = catOther;
112 for (int i = 'a'; i <= 'z'; ++i)
113 theCatcode[i] = catLetter;
114 for (int i = 'A'; i <= 'Z'; ++i)
115 theCatcode[i] = catLetter;
117 theCatcode['\\'] = catEscape;
118 theCatcode['{'] = catBegin;
119 theCatcode['}'] = catEnd;
120 theCatcode['$'] = catMath;
121 theCatcode['&'] = catAlign;
122 theCatcode['\n'] = catNewline;
123 theCatcode['#'] = catParameter;
124 theCatcode['^'] = catSuper;
125 theCatcode['_'] = catSub;
126 theCatcode['
\7f'] = catIgnore;
127 theCatcode[' '] = catSpace;
128 theCatcode['\t'] = catSpace;
129 theCatcode['\r'] = catSpace;
130 theCatcode['~'] = catActive;
131 theCatcode['%'] = catComment;
137 // Helper class for parsing
143 Token() : cs_(), char_(0), cat_(catIgnore) {}
145 Token(char c, CatCode cat) : cs_(), char_(c), cat_(cat) {}
147 Token(const string & cs) : cs_(cs), char_(0), cat_(catIgnore) {}
150 string const & cs() const { return cs_; }
152 CatCode cat() const { return cat_; }
154 char character() const { return char_; }
156 string asString() const;
167 string Token::asString() const
169 return cs_.size() ? cs_ : string(1, char_);
172 bool operator==(Token const & s, Token const & t)
174 return s.character() == t.character()
175 && s.cat() == t.cat() && s.cs() == t.cs();
178 bool operator!=(Token const & s, Token const & t)
183 ostream & operator<<(ostream & os, Token const & t)
186 os << "\\" << t.cs();
188 os << "[" << t.character() << "," << t.cat() << "]";
197 Parser(LyXLex & lex);
199 Parser(istream & is);
202 MathMacroTemplate * parse_macro();
204 MathMatrixInset * parse_normal();
206 void parse_into(MathArray & array, unsigned flags, MathTextCodes = LM_TC_MIN);
208 int lineno() const { return lineno_; }
214 string getArg(char lf, char rf);
218 void error(string const & msg);
220 void parse_lines(MathGridInset * p, bool numbered, bool outmost);
222 latexkeys const * read_delim();
226 void tokenize(istream & is);
228 void tokenize(string const & s);
230 void push_back(Token const & t);
234 Token const & prevToken() const;
236 Token const & nextToken() const;
238 Token const & getToken();
240 void lex(string const & s);
247 std::vector<Token> tokens_;
259 Parser::Parser(LyXLex & lexer)
260 : lineno_(lexer.getLineNo()), pos_(0), curr_num_(false)
262 tokenize(lexer.getStream());
267 Parser::Parser(istream & is)
268 : lineno_(0), pos_(0), curr_num_(false)
274 void Parser::push_back(Token const & t)
276 tokens_.push_back(t);
280 void Parser::pop_back()
286 Token const & Parser::prevToken() const
288 static const Token dummy;
289 return pos_ > 0 ? tokens_[pos_ - 1] : dummy;
293 Token const & Parser::nextToken() const
295 static const Token dummy;
296 return good() ? tokens_[pos_] : dummy;
300 Token const & Parser::getToken()
302 static const Token dummy;
303 return good() ? tokens_[pos_++] : dummy;
307 void Parser::putback()
313 bool Parser::good() const
315 return pos_ < tokens_.size();
319 char Parser::getChar()
322 lyxerr << "The input stream is not well..." << endl;
323 return tokens_[pos_++].character();
327 string Parser::getArg(char lf, char rg)
335 while ((c = getChar()) != rg && good())
342 void Parser::tokenize(istream & is)
344 // eat everything up to the next \end_inset or end of stream
345 // and store it in s for further tokenization
350 if (s.size() >= 10 && s.substr(s.size() - 10) == "\\end_inset") {
351 s = s.substr(0, s.size() - 10);
361 void Parser::tokenize(string const & buffer)
363 static bool init_done = false;
370 istringstream is(buffer.c_str(), ios::in | ios::binary);
375 switch (catcode(c)) {
379 if (catcode(c) == catNewline)
380 ; //push_back(Token("par"));
382 push_back(Token(' ', catSpace));
389 while (is.get(c) && catcode(c) != catNewline)
398 if (catcode(c) == catLetter) {
399 while (is.get(c) && catcode(c) == catLetter)
401 if (catcode(c) == catSpace)
402 while (is.get(c) && catcode(c) == catSpace)
411 push_back(Token(c, catcode(c)));
416 lyxerr << "\nTokens: ";
417 for (unsigned i = 0; i < tokens_.size(); ++i)
418 lyxerr << tokens_[i];
424 void Parser::error(string const & msg)
426 lyxerr << "Line ~" << lineno_ << ": Math parse error: " << msg << endl;
430 void Parser::parse_lines(MathGridInset * p, bool numbered, bool outmost)
432 const int cols = p->ncols();
434 // save global variables
435 bool const saved_num = curr_num_;
436 string const saved_label = curr_label_;
438 for (int row = 0; true; ++row) {
439 // reset global variables
440 curr_num_ = numbered;
444 for (int col = 0; col < cols; ++col) {
445 //lyxerr << "reading cell " << row << " " << col << "\n";
446 parse_into(p->cell(col + row * cols), FLAG_BLOCK);
449 if (prevToken().cat() != catAlign) {
450 //lyxerr << "less cells read than normal in row/col: "
451 // << row << " " << col << "\n";
457 MathMatrixInset * m = static_cast<MathMatrixInset *>(p);
458 m->numbered(row, curr_num_);
459 m->label(row, curr_label_);
460 if (curr_skip_.size()) {
461 m->vskip(LyXLength(curr_skip_), row);
467 if (prevToken() != Token("\\")) {
468 //lyxerr << "no newline here\n";
475 // restore "global" variables
476 curr_num_ = saved_num;
477 curr_label_ = saved_label;
481 MathMacroTemplate * Parser::parse_macro()
483 while (nextToken().cat() == catSpace)
486 if (getToken().cs() != "newcommand") {
487 lyxerr << "\\newcommand expected\n";
491 if (getToken().cat() != catBegin) {
492 lyxerr << "'{' expected\n";
496 string name = getToken().cs();
498 if (getToken().cat() != catEnd) {
499 lyxerr << "'}' expected\n";
503 string arg = getArg('[', ']');
504 int narg = arg.empty() ? 0 : atoi(arg.c_str());
505 //lyxerr << "creating macro " << name << " with " << narg << "args\n";
506 MathMacroTemplate * p = new MathMacroTemplate(name, narg);
507 parse_into(p->cell(0), FLAG_BRACE | FLAG_BRACE_LAST);
512 MathMatrixInset * Parser::parse_normal()
514 while (nextToken().cat() == catSpace)
517 Token const & t = getToken();
519 if (t.cat() == catMath || t.cs() == "(") {
520 MathMatrixInset * p = new MathMatrixInset(LM_OT_SIMPLE);
521 parse_into(p->cell(0), 0);
525 if (!t.cs().size()) {
526 lyxerr << "start of math expected, got '" << t << "'\n";
530 string const & cs = t.cs();
535 MathMatrixInset * p = new MathMatrixInset(LM_OT_EQUATION);
536 parse_into(p->cell(0), 0);
537 p->numbered(0, curr_num_);
538 p->label(0, curr_label_);
543 lyxerr << "'begin' of un-simple math expected, got '" << cs << "'\n";
547 string const name = getArg('{', '}');
549 if (name == "equation" || name == "equation*") {
550 curr_num_ = !stared(name);
552 MathMatrixInset * p = new MathMatrixInset(LM_OT_EQUATION);
553 parse_into(p->cell(0), FLAG_END);
554 p->numbered(0, curr_num_);
555 p->label(0, curr_label_);
559 if (name == "eqnarray" || name == "eqnarray*") {
560 MathMatrixInset * p = new MathMatrixInset(LM_OT_EQNARRAY);
561 parse_lines(p, !stared(name), true);
565 if (name == "align" || name == "align*") {
566 MathMatrixInset * p = new MathMatrixInset(LM_OT_ALIGN);
567 parse_lines(p, !stared(name), true);
571 if (name == "alignat" || name == "alignat*") {
572 MathMatrixInset * p =
573 new MathMatrixInset(LM_OT_ALIGNAT, 2 * atoi(getArg('{', '}').c_str()));
574 parse_lines(p, !stared(name), true);
578 if (name == "xalignat" || name == "xalignat*") {
579 MathMatrixInset * p =
580 new MathMatrixInset(LM_OT_XALIGNAT, 2 * atoi(getArg('{', '}').c_str()));
581 parse_lines(p, !stared(name), true);
585 if (name == "xxalignat") {
586 MathMatrixInset * p =
587 new MathMatrixInset(LM_OT_XXALIGNAT, 2 * atoi(getArg('{', '}').c_str()));
588 parse_lines(p, !stared(name), true);
592 if (name == "multline" || name == "multline*") {
593 MathMatrixInset * p = new MathMatrixInset(LM_OT_MULTLINE);
594 parse_lines(p, !stared(name), true);
598 if (name == "gather" || name == "gather*") {
599 MathMatrixInset * p = new MathMatrixInset(LM_OT_GATHER);
600 parse_lines(p, !stared(name), true);
604 lyxerr[Debug::MATHED] << "1: unknown math environment: " << name << "\n";
609 latexkeys const * Parser::read_delim()
611 Token const & t = getToken();
612 latexkeys const * l = in_word_set(t.asString());
613 return l ? l : in_word_set(".");
617 void Parser::parse_into(MathArray & array, unsigned flags, MathTextCodes code)
619 MathTextCodes yyvarcode = LM_TC_MIN;
624 Token const & t = getToken();
626 //lyxerr << "t: " << t << " flags: " << flags << "'\n";
627 //array.dump(lyxerr);
630 if (flags & FLAG_ITEM) {
632 if (t.cat() == catBegin) {
633 // skip the brace and collect everything to the next matching
635 flags |= FLAG_BRACE_LAST;
638 // handle only this single token, leave the loop if done
643 if (flags & FLAG_BRACE) {
644 if (t.cat() != catBegin) {
645 error("Expected {. Maybe you forgot to enclose an argument in {}");
649 flags &= ~FLAG_BRACE;
654 if (flags & FLAG_BLOCK) {
655 if (t.cat() == catAlign || t.cs() == "\\")
657 if (t.cs() == "end") {
666 if (t.cat() == catMath)
669 else if (t.cat() == catLetter)
670 array.push_back(new MathCharInset(t.character(), yyvarcode));
672 else if (t.cat() == catSpace &&
673 (yyvarcode == LM_TC_TEXTRM || code == LM_TC_TEXTRM))
674 array.push_back(new MathCharInset(' ', yyvarcode));
676 else if (t.cat() == catParameter) {
677 Token const & n = getToken();
678 MathMacroArgument * p = new MathMacroArgument(n.character() - '0');
682 else if (t.cat() == catBegin) {
683 array.push_back(new MathCharInset('{', LM_TC_TEX));
686 else if (t.cat() == catEnd) {
687 if (flags & FLAG_BRACE_LAST)
689 array.push_back(new MathCharInset('}', LM_TC_TEX));
692 else if (t.cat() == catAlign) {
693 lyxerr << "found tab unexpectedly, array: '" << array << "'\n";
694 array.push_back(new MathCharInset('&', LM_TC_TEX));
697 else if (t.cat() == catSuper || t.cat() == catSub) {
698 bool up = (t.cat() == catSuper);
700 array.push_back(new MathCharInset(' '));
701 parse_into(array.back().ensure(up)->cell(0), FLAG_ITEM);
704 else if (t.character() == ']' && (flags & FLAG_BRACK_END))
707 else if (t.cat() == catOther)
708 array.push_back(new MathCharInset(t.character(), yyvarcode));
713 else if (t.cs() == "protect")
716 else if (t.cs() == "end")
719 else if (t.cs() == ")")
722 else if (t.cs() == "]")
725 else if (t.cs() == "\\") {
726 curr_skip_ = getArg('[', ']');
727 if (flags & FLAG_NEWLINE)
729 lyxerr[Debug::MATHED]
730 << "found newline unexpectedly, array: '" << array << "'\n";
731 array.push_back(createMathInset("\\"));
734 else if (t.cs() == "limits" && array.size())
735 array.back().limits(1);
737 else if (t.cs() == "nolimits" && array.size())
738 array.back().limits(-1);
740 else if (t.cs() == "nonumber")
743 else if (t.cs() == "number")
746 else if (t.cs() == "sqrt") {
749 array.push_back(new MathRootInset);
750 parse_into(array.back().nucleus()->cell(0), FLAG_BRACK_END);
751 parse_into(array.back().nucleus()->cell(1), FLAG_ITEM);
754 array.push_back(new MathSqrtInset);
755 parse_into(array.back().nucleus()->cell(0), FLAG_ITEM);
759 else if (t.cs() == "left") {
760 latexkeys const * l = read_delim();
762 parse_into(ar, FLAG_RIGHT);
763 latexkeys const * r = read_delim();
764 MathDelimInset * dl = new MathDelimInset(l, r);
769 else if (t.cs() == "right") {
770 if (!(flags & FLAG_RIGHT))
771 error("Unmatched right delimiter");
778 lyxerr[Debug::MATHED] << "LM_TK_STY not implemented\n";
779 //MathArray tmp = array;
780 //MathSizeInset * p = new MathSizeInset(MathStyles(lval_->id));
781 //array.push_back(p);
782 //parse_into(p->cell(0), FLAG_BRACE_FONT);
787 array.push_back(new MathCharInset(ival_, LM_TC_TEX));
791 else if (t.cs() == "begin") {
792 string const name = getArg('{', '}');
793 if (name == "array") {
794 string const valign = getArg('[', ']') + 'c';
795 string const halign = getArg('{', '}');
796 MathArrayInset * m = new MathArrayInset(halign.size(), 1);
797 m->valign(valign[0]);
799 parse_lines(m, false, false);
801 } else if (name == "split") {
802 MathSplitInset * m = new MathSplitInset(1);
803 parse_lines(m, false, false);
806 lyxerr[Debug::MATHED] << "unknow math inset begin '" << name << "'\n";
809 else if (t.cs() == "kern") {
815 Token const & t = getToken();
821 if (isValidLength(s))
824 array.push_back(new MathKernInset(s));
827 else if (t.cs() == "label") {
829 //parse_into(ar, FLAG_ITEM);
831 //ar.write(os, true);
832 //curr_label_ = os.str();
834 curr_label_ = getArg('{', '}');
837 else if (t.cs() == "choose" || t.cs() == "over" || t.cs() == "atop") {
838 MathInset * p = createMathInset(t.cs());
839 // search backward for position of last '{' if any
841 for (pos = array.size() - 1; pos >= 0; --pos)
842 if (array.at(pos)->nucleus()->getChar() == '{')
845 // found it -> use the part after '{' as "numerator", erase the '{'
846 p->cell(0) = MathArray(array, pos + 1, array.size());
847 array.erase(pos, array.size());
849 // not found -> use everything as "numerator"
850 p->cell(0).swap(array);
852 parse_into(p->cell(1), FLAG_BLOCK);
856 else if (t.cs().size()) {
857 latexkeys const * l = in_word_set(t.cs());
859 if (l->token == LM_TK_FONT) {
860 //lyxerr << "starting font\n";
861 //CatCode catSpaceSave = theCatcode[' '];
862 //if (l->id == LM_TC_TEXTRM) {
863 // // temporarily change catcode
864 // theCatcode[' '] = catLetter;
867 MathTextCodes t = static_cast<MathTextCodes>(l->id);
869 parse_into(ar, FLAG_ITEM, t);
870 for (MathArray::iterator it = ar.begin(); it != ar.end(); ++it)
871 it->nucleus()->handleFont(t);
874 // undo catcode changes
875 ////theCatcode[' '] = catSpaceSave;
876 //lyxerr << "ending font\n";
879 else if (l->token == LM_TK_OLDFONT)
880 yyvarcode = static_cast<MathTextCodes>(l->id);
883 MathInset * p = createMathInset(t.cs());
884 for (int i = 0; i < p->nargs(); ++i)
885 parse_into(p->cell(i), FLAG_ITEM);
891 MathInset * p = createMathInset(t.cs());
893 for (int i = 0; i < p->nargs(); ++i)
894 parse_into(p->cell(i), FLAG_ITEM);
897 error("Unrecognized token");
898 //lyxerr[Debug::MATHED] << "[" << t << "]\n";
905 if (flags & FLAG_LEAVE) {
906 flags &= ~FLAG_LEAVE;
912 lyxerr << " Math Panic, expect problems!\n";
913 // Search for the end command.
917 } while (good() && t.cs() != "end");
921 } // anonymous namespace
925 MathArray mathed_parse_cell(string const & str)
927 istringstream is(str.c_str());
930 parser.parse_into(ar, 0);
936 MathMacroTemplate * mathed_parse_macro(string const & str)
938 istringstream is(str.c_str());
940 return parser.parse_macro();
943 MathMacroTemplate * mathed_parse_macro(istream & is)
946 return parser.parse_macro();
949 MathMacroTemplate * mathed_parse_macro(LyXLex & lex)
952 return parser.parse_macro();
957 MathMatrixInset * mathed_parse_normal(string const & str)
959 istringstream is(str.c_str());
961 return parser.parse_normal();
964 MathMatrixInset * mathed_parse_normal(istream & is)
967 return parser.parse_normal();
970 MathMatrixInset * mathed_parse_normal(LyXLex & lex)
973 return parser.parse_normal();