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_macro.h"
35 #include "math_macrotable.h"
36 #include "math_macrotemplate.h"
37 #include "math_matrixinset.h"
38 #include "math_rootinset.h"
39 #include "math_scopeinset.h"
40 #include "math_sqrtinset.h"
41 #include "math_scriptinset.h"
42 #include "math_sqrtinset.h"
46 #include "support/lstrings.h"
56 bool stared(string const & s)
58 unsigned n = s.size();
59 return n && s[n - 1] == '*';
62 MathScriptInset * prevScriptInset(MathArray const & array)
64 MathInset * p = array.back();
65 return (p && p->isScriptInset()) ? static_cast<MathScriptInset *>(p) : 0;
69 MathInset * lastScriptInset(MathArray & array, bool up, int limits)
71 MathScriptInset * p = prevScriptInset(array);
73 MathInset * b = array.back();
74 if (b && b->isScriptable()) {
75 p = new MathScriptInset(up, !up, b->clone());
78 p = new MathScriptInset(up, !up);
92 // These are TeX's catcodes
94 catEscape, // 0 backslash
104 catSpace, // 10 space
105 catLetter, // 11 a-zA-Z
106 catOther, // 12 none of the above
109 catInvalid // 15 <delete>
112 CatCode theCatcode[256];
115 inline CatCode catcode(unsigned char c)
117 return theCatcode[c];
121 const unsigned char LM_TK_OPEN = '{';
122 const unsigned char LM_TK_CLOSE = '}';
125 FLAG_BRACE = 1 << 0, // an opening brace needed
126 FLAG_BRACE_LAST = 1 << 1, // last closing brace ends the parsing process
127 FLAG_RIGHT = 1 << 2, // next \\right ends the parsing process
128 FLAG_END = 1 << 3, // next \\end ends the parsing process
129 FLAG_BRACK_END = 1 << 4, // next closing bracket ends the parsing process
130 FLAG_NEWLINE = 1 << 6, // next \\\\ ends the parsing process
131 FLAG_ITEM = 1 << 7, // read a (possibly braced token)
132 FLAG_BLOCK = 1 << 8, // next block ends the parsing process
133 FLAG_LEAVE = 1 << 9 // leave the loop at the end
139 for (int i = 0; i <= 255; ++i)
140 theCatcode[i] = catOther;
141 for (int i = 'a'; i <= 'z'; ++i)
142 theCatcode[i] = catLetter;
143 for (int i = 'A'; i <= 'Z'; ++i)
144 theCatcode[i] = catLetter;
146 theCatcode['\\'] = catEscape;
147 theCatcode['{'] = catBegin;
148 theCatcode['}'] = catEnd;
149 theCatcode['$'] = catMath;
150 theCatcode['&'] = catAlign;
151 theCatcode['\n'] = catNewline;
152 theCatcode['#'] = catParameter;
153 theCatcode['^'] = catSuper;
154 theCatcode['_'] = catSub;
155 theCatcode['
\7f'] = catIgnore;
156 theCatcode[' '] = catSpace;
157 theCatcode['\t'] = catSpace;
158 theCatcode['\r'] = catSpace;
159 theCatcode['~'] = catActive;
160 theCatcode['%'] = catComment;
166 // Helper class for parsing
172 Token() : cs_(), char_(0), cat_(catIgnore) {}
174 Token(char c, CatCode cat) : cs_(), char_(c), cat_(cat) {}
176 Token(const string & cs) : cs_(cs), char_(0), cat_(catIgnore) {}
179 bool operator==(Token const & t) const;
181 bool operator!=(Token const & t) const;
183 string const & cs() const { return cs_; }
185 CatCode cat() const { return cat_; }
187 char character() const { return char_; }
189 string asString() const;
200 string Token::asString() const
202 return cs_.size() ? cs_ : string(1, char_);
205 bool Token::operator==(Token const & t) const
207 return char_ == t.char_ && cat_ == t.cat_ && cs_ == t.cs_;
210 bool Token::operator!=(Token const & t) const
212 return char_ != t.char_ && cat_ != t.cat_ && cs_ != t.cs_;
215 ostream & operator<<(ostream & os, Token const & t)
218 os << "\\" << t.cs();
220 os << "[" << t.character() << "," << t.cat() << "]";
229 Parser(LyXLex & lex);
231 Parser(istream & is);
234 MathMacroTemplate * parse_macro();
236 MathMatrixInset * parse_normal();
238 void parse_into(MathArray & array, unsigned flags);
240 int lineno() const { return lineno_; }
246 string getArg(char lf, char rf);
250 void error(string const & msg);
252 void parse_lines(MathGridInset * p, bool numbered, bool outmost);
254 latexkeys const * read_delim();
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)
294 tokenize(lexer.getStream());
298 Parser::Parser(istream & is)
299 : lineno_(0), pos_(0)
305 void Parser::push_back(Token const & t)
307 tokens_.push_back(t);
311 void Parser::pop_back()
317 Token const & Parser::prevToken() const
319 static const Token dummy;
320 return pos_ > 0 ? tokens_[pos_ - 1] : dummy;
324 Token const & Parser::nextToken() const
326 static const Token dummy;
327 return good() ? tokens_[pos_] : dummy;
331 Token const & Parser::getToken()
333 static const Token dummy;
334 return good() ? tokens_[pos_++] : dummy;
338 void Parser::putback()
344 bool Parser::good() const
346 return pos_ < tokens_.size();
350 char Parser::getChar()
353 lyxerr << "The input stream is not well..." << endl;
354 return tokens_[pos_++].character();
358 string Parser::getArg(char lf, char rg)
366 while ((c = getChar()) != rg && good())
373 void Parser::tokenize(istream & is)
375 // eat everything up to the next \end_inset or end of stream
376 // and store it in s for further tokenization
381 if (s.size() >= 10 && s.substr(s.size() - 10) == "\\end_inset") {
382 s = s.substr(0, s.size() - 10);
392 void Parser::tokenize(string const & buffer)
394 static bool init_done = false;
401 istringstream is(buffer, ios::in || ios::binary);
406 switch (catcode(c)) {
410 if (catcode(c) == catNewline)
411 ; //push_back(Token("par"));
413 push_back(Token(' ', catSpace));
420 while (is.get(c) && catcode(c) != catNewline)
429 if (catcode(c) == catLetter) {
430 while (is.get(c) && catcode(c) == catLetter)
432 if (catcode(c) == catSpace)
433 while (is.get(c) && catcode(c) == catSpace)
442 push_back(Token(c, catcode(c)));
446 //lyxerr << "\nTokens: ";
447 //for (unsigned i = 0; i < tokens_.size(); ++i)
448 // lyxerr << tokens_[i];
453 void Parser::error(string const & msg)
455 lyxerr << "Line ~" << lineno_ << ": Math parse error: " << msg << endl;
459 void Parser::parse_lines(MathGridInset * p, bool numbered, bool outmost)
461 const int cols = p->ncols();
463 // save global variables
464 bool const saved_num = curr_num_;
465 string const saved_label = curr_label_;
467 for (int row = 0; true; ++row) {
468 // reset global variables
469 curr_num_ = numbered;
473 for (int col = 0; col < cols; ++col) {
474 //lyxerr << "reading cell " << row << " " << col << "\n";
475 parse_into(p->cell(col + row * cols), FLAG_BLOCK);
478 if (prevToken().cat() != catAlign) {
479 //lyxerr << "less cells read than normal in row/col: "
480 // << row << " " << col << "\n";
486 MathMatrixInset * m = static_cast<MathMatrixInset *>(p);
487 m->numbered(row, curr_num_);
488 m->label(row, curr_label_);
489 if (curr_skip_.size()) {
490 m->vskip(LyXLength(curr_skip_), row);
496 if (prevToken() != Token("\\")) {
497 //lyxerr << "no newline here\n";
504 // restore "global" variables
505 curr_num_ = saved_num;
506 curr_label_ = saved_label;
510 MathMacroTemplate * Parser::parse_macro()
512 while (nextToken().cat() == catSpace)
515 if (getToken().cs() != "newcommand") {
516 lyxerr << "\\newcommand expected\n";
520 if (getToken().cat() != catBegin) {
521 lyxerr << "'{' expected\n";
525 string name = getToken().cs();
527 if (getToken().cat() != catEnd) {
528 lyxerr << "'}' expected\n";
532 string arg = getArg('[', ']');
533 int narg = arg.empty() ? 0 : atoi(arg.c_str());
534 //lyxerr << "creating macro " << name << " with " << narg << "args\n";
535 MathMacroTemplate * p = new MathMacroTemplate(name, narg);
536 parse_into(p->cell(0), FLAG_BRACE | FLAG_BRACE_LAST);
541 MathMatrixInset * Parser::parse_normal()
543 Token const & t = getToken();
545 if (t.cat() == catMath || t.cs() == "(") {
546 MathMatrixInset * p = new MathMatrixInset(LM_OT_SIMPLE);
547 parse_into(p->cell(0), 0);
551 if (!t.cs().size()) {
552 lyxerr << "start of math expected, got '" << t << "'\n";
556 string const & cs = t.cs();
561 MathMatrixInset * p = new MathMatrixInset(LM_OT_EQUATION);
562 parse_into(p->cell(0), 0);
563 p->numbered(0, curr_num_);
564 p->label(0, curr_label_);
569 lyxerr << "'begin' of un-simple math expected, got '" << cs << "'\n";
573 string const name = getArg('{', '}');
575 if (name == "equation" || name == "equation*") {
576 curr_num_ = stared(name);
578 MathMatrixInset * p = new MathMatrixInset(LM_OT_EQUATION);
579 parse_into(p->cell(0), FLAG_END);
580 p->numbered(0, curr_num_);
581 p->label(0, curr_label_);
585 if (name == "eqnarray" || name == "eqnarray*") {
586 MathMatrixInset * p = new MathMatrixInset(LM_OT_EQNARRAY);
587 parse_lines(p, stared(name), true);
591 if (name == "align" || name == "align*") {
592 MathMatrixInset * p = new MathMatrixInset(LM_OT_ALIGN);
593 p->halign(getArg('{', '}'));
594 parse_lines(p, stared(name), true);
598 if (name == "alignat" || name == "alignat*") {
599 MathMatrixInset * p = new MathMatrixInset(LM_OT_ALIGNAT);
600 p->halign(getArg('{', '}'));
601 parse_lines(p, stared(name), true);
605 lyxerr[Debug::MATHED] << "1: unknown math environment: " << name << "\n";
610 latexkeys const * Parser::read_delim()
612 Token const & t = getToken();
613 latexkeys const * l = in_word_set(t.asString());
614 return l ? l : in_word_set(".");
618 void Parser::parse_into(MathArray & array, unsigned flags)
620 MathTextCodes yyvarcode = LM_TC_MIN;
626 Token const & t = getToken();
628 lyxerr << "t: " << t << " flags: " << flags << "'\n";
629 //array.dump(lyxerr);
632 if (flags & FLAG_ITEM) {
634 if (t.cat() == catBegin) {
635 // skip the brace and collect everything to the next matching
637 flags |= FLAG_BRACE_LAST;
640 // handle only this single token, leave the loop if done
645 if (flags & FLAG_BRACE) {
646 if (t.cat() != catBegin) {
647 error("Expected {. Maybe you forgot to enclose an argument in {}");
651 flags &= ~FLAG_BRACE;
656 if (flags & FLAG_BLOCK) {
657 if (t.cat() == catEnd || t.cat() == catAlign || t.cs() == "\\")
659 if (t.cs() == "end") {
668 if (t.cat() == catMath)
671 else if (t.cat() == catLetter)
672 array.push_back(new MathCharInset(t.character(), yyvarcode));
674 else if (t.cat() == catSpace && yyvarcode == LM_TC_TEXTRM)
675 array.push_back(new MathCharInset(' ', yyvarcode));
677 else if (t.cat() == catParameter) {
678 Token const & n = getToken();
679 MathMacroArgument * p = new MathMacroArgument(n.character() - '0');
683 else if (t.cat() == catBegin) {
684 //lyxerr << " creating ScopeInset\n";
685 array.push_back(new MathScopeInset);
686 parse_into(array.back()->cell(0), FLAG_BRACE_LAST);
689 else if (t.cat() == catEnd) {
690 if (!(flags & FLAG_BRACE_LAST))
691 lyxerr << " ##### unexpected end of block\n";
695 else if (t.cat() == catAlign) {
696 lyxerr << "found tab unexpectedly, array: '" << array << "'\n";
700 else if (t.cat() == catSuper)
701 parse_into(lastScriptInset(array, true, limits)->cell(0), FLAG_ITEM);
703 else if (t.cat() == catSub)
704 parse_into(lastScriptInset(array, false, limits)->cell(1), FLAG_ITEM);
706 else if (t.character() == ']' && (flags & FLAG_BRACK_END))
709 else if (t.cat() == catOther)
710 array.push_back(new MathCharInset(t.character(), yyvarcode));
715 else if (t.cs() == "protect")
718 else if (t.cs() == "end")
721 else if (t.cs() == ")")
724 else if (t.cs() == "]")
727 else if (t.cs() == "\\") {
728 curr_skip_ = getArg('[', ']');
729 if (!(flags & FLAG_NEWLINE))
730 lyxerr[Debug::MATHED]
731 << "found newline unexpectedly, array: '" << array << "'\n";
735 else if (t.cs() == "limits")
738 else if (t.cs() == "nolimits")
741 else if (t.cs() == "nonumber")
744 else if (t.cs() == "number")
747 else if (t.cs() == "sqrt") {
750 array.push_back(new MathRootInset);
751 parse_into(array.back()->cell(0), FLAG_BRACK_END);
752 parse_into(array.back()->cell(1), FLAG_ITEM);
755 array.push_back(new MathSqrtInset);
756 parse_into(array.back()->cell(0), FLAG_ITEM);
760 else if (t.cs() == "left") {
761 latexkeys const * l = read_delim();
763 parse_into(ar, FLAG_RIGHT);
764 latexkeys const * r = read_delim();
765 MathDelimInset * dl = new MathDelimInset(l, r);
770 else if (t.cs() == "right") {
771 if (!(flags & FLAG_RIGHT))
772 error("Unmatched right delimiter");
779 lyxerr[Debug::MATHED] << "LM_TK_STY not implemented\n";
780 //MathArray tmp = array;
781 //MathSizeInset * p = new MathSizeInset(MathStyles(lval_->id));
782 //array.push_back(p);
783 //parse_into(p->cell(0), FLAG_BRACE_FONT);
788 if (MathMacroTable::hasTemplate(sval_)) {
789 MathMacro * m = MathMacroTable::cloneTemplate(sval_);
790 for (int i = 0; i < m->nargs(); ++i)
791 parse_into(m->cell(i), FLAG_ITEM);
793 m->metrics(LM_ST_TEXT);
795 array.push_back(new MathFuncInset(sval_));
799 array.push_back(new MathCharInset(ival_, LM_TC_SPECIAL));
803 else if (t.cs() == "begin") {
804 string const name = getArg('{', '}');
805 if (name == "array") {
806 string const valign = getArg('[', ']') + 'c';
807 string const halign = getArg('{', '}');
808 MathArrayInset * m = new MathArrayInset(halign.size(), 1);
809 m->valign(valign[0]);
811 parse_lines(m, false, false);
814 lyxerr[Debug::MATHED] << "unknow math inset begin '" << name << "'\n";
817 else if (t.cs() == "label") {
819 parse_into(ar, FLAG_ITEM);
822 curr_label_ = os.str();
824 //curr_label_ = getArg('{', '}');
827 else if (t.cs() == "choose" || t.cs() == "over") {
829 MathInset * p = createMathInset(t.cs());
830 p->cell(0).swap(array);
832 parse_into(p->cell(1), FLAG_BLOCK);
835 else if (t.cs().size()) {
837 latexkeys const * l = in_word_set(t.cs());
839 if (l->token == LM_TK_FONT) {
840 //lyxerr << "starting font\n";
842 parse_into(ar, FLAG_ITEM);
843 for (MathArray::iterator it = ar.begin(); it != ar.end(); ++it)
844 (*it)->handleFont(static_cast<MathTextCodes>(l->id));
846 //lyxerr << "ending font\n";
849 else if (l->token == LM_TK_OLDFONT)
850 yyvarcode = static_cast<MathTextCodes>(l->id);
853 MathInset * p = createMathInset(t.cs());
854 for (int i = 0; i < p->nargs(); ++i)
855 parse_into(p->cell(i), FLAG_ITEM);
861 MathInset * p = createMathInset(t.cs());
863 for (int i = 0; i < p->nargs(); ++i)
864 parse_into(p->cell(i), FLAG_ITEM);
867 error("Unrecognized token");
868 //lyxerr[Debug::MATHED] << "[" << t << "]\n";
875 if (flags & FLAG_LEAVE) {
876 flags &= ~FLAG_LEAVE;
882 lyxerr << " Math Panic, expect problems!\n";
883 // Search for the end command.
887 } while (good() && t.cs() != "end");
891 } // anonymous namespace
895 MathArray mathed_parse_cell(string const & str)
897 istringstream is(str.c_str());
900 parser.parse_into(ar, 0);
906 MathMacroTemplate * mathed_parse_macro(string const & str)
908 istringstream is(str.c_str());
910 return parser.parse_macro();
913 MathMacroTemplate * mathed_parse_macro(istream & is)
916 return parser.parse_macro();
919 MathMacroTemplate * mathed_parse_macro(LyXLex & lex)
922 return parser.parse_macro();
927 MathMatrixInset * mathed_parse_normal(string const & str)
929 istringstream is(str.c_str());
931 return parser.parse_normal();
934 MathMatrixInset * mathed_parse_normal(istream & is)
937 return parser.parse_normal();
940 MathMatrixInset * mathed_parse_normal(LyXLex & lex)
943 return parser.parse_normal();