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"
54 bool stared(string const & s)
56 unsigned n = s.size();
57 return n && s[n - 1] == '*';
60 MathScriptInset * prevScriptInset(MathArray const & array)
62 MathInset * p = array.back();
63 return (p && p->isScriptInset()) ? static_cast<MathScriptInset *>(p) : 0;
67 MathInset * lastScriptInset(MathArray & array, bool up, int limits)
69 MathScriptInset * p = prevScriptInset(array);
71 MathInset * b = array.back();
72 if (b && b->isScriptable()) {
73 p = new MathScriptInset(up, !up, b->clone());
76 p = new MathScriptInset(up, !up);
90 // These are TeX's catcodes
92 catEscape, // 0 backslash
102 catSpace, // 10 space
103 catLetter, // 11 a-zA-Z
104 catOther, // 12 none of the above
107 catInvalid // 15 <delete>
110 CatCode theCatcode[256];
113 inline CatCode catcode(unsigned char c)
115 return theCatcode[c];
119 const unsigned char LM_TK_OPEN = '{';
120 const unsigned char LM_TK_CLOSE = '}';
123 FLAG_BRACE = 1 << 0, // an opening brace needed
124 FLAG_BRACE_LAST = 1 << 1, // last closing brace ends the parsing process
125 FLAG_RIGHT = 1 << 2, // next \\right ends the parsing process
126 FLAG_END = 1 << 3, // next \\end ends the parsing process
127 FLAG_BRACK_END = 1 << 4, // next closing bracket ends the parsing process
128 FLAG_NEWLINE = 1 << 6, // next \\\\ ends the parsing process
129 FLAG_ITEM = 1 << 7, // read a (possibly braced token)
130 FLAG_BLOCK = 1 << 8, // next block ends the parsing process
131 FLAG_LEAVE = 1 << 9, // leave the loop at the end
137 for (int i = 0; i <= 255; ++i)
138 theCatcode[i] = catOther;
139 for (int i = 'a'; i <= 'z'; ++i)
140 theCatcode[i] = catLetter;
141 for (int i = 'A'; i <= 'Z'; ++i)
142 theCatcode[i] = catLetter;
144 theCatcode['\\'] = catEscape;
145 theCatcode['{'] = catBegin;
146 theCatcode['}'] = catEnd;
147 theCatcode['$'] = catMath;
148 theCatcode['&'] = catAlign;
149 theCatcode['\n'] = catNewline;
150 theCatcode['#'] = catParameter;
151 theCatcode['^'] = catSuper;
152 theCatcode['_'] = catSub;
153 theCatcode['
\7f'] = catIgnore;
154 theCatcode[' '] = catSpace;
155 theCatcode['\t'] = catSpace;
156 theCatcode['\r'] = catSpace;
157 theCatcode['~'] = catActive;
158 theCatcode['%'] = catComment;
164 // Helper class for parsing
170 Token() : cs_(), char_(0), cat_(catIgnore) {}
172 Token(char c, CatCode cat) : cs_(), char_(c), cat_(cat) {}
174 Token(const string & cs) : cs_(cs), char_(0), cat_(catIgnore) {}
177 bool operator==(Token const & t) const;
179 string const & cs() const { return cs_; }
181 CatCode cat() const { return cat_; }
183 char character() const { return char_; }
185 string asString() const;
196 string Token::asString() const
198 return cs_.size() ? cs_ : string(1, char_);
201 bool Token::operator==(Token const & t) const
203 return char_ == t.char_ && cat_ == t.cat_ && cs_ == t.cs_;
206 ostream & operator<<(ostream & os, Token const & t)
209 os << "\\" << t.cs();
211 os << "[" << t.character() << "," << t.cat() << "]";
220 Parser(LyXLex & lex);
222 Parser(istream & is);
225 MathMacroTemplate * parse_macro();
227 MathMatrixInset * parse_normal();
229 void parse_into(MathArray & array, unsigned flags);
231 int lineno() const { return lineno_; }
237 string getArg(char lf, char rf);
241 void error(string const & msg);
243 void parse_lines(MathGridInset * p, bool numbered, bool outmost);
245 latexkeys const * read_delim();
249 void tokenize(istream & is);
251 void tokenize(string const & s);
253 void push_back(Token const & t);
257 Token const & prevToken() const;
259 Token const & nextToken() const;
261 Token const & getToken();
263 void lex(string const & s);
270 std::vector<Token> tokens_;
282 Parser::Parser(LyXLex & lexer)
283 : lineno_(lexer.getLineNo()), pos_(0)
285 tokenize(lexer.getStream());
289 Parser::Parser(istream & is)
290 : lineno_(0), pos_(0)
296 void Parser::push_back(Token const & t)
298 tokens_.push_back(t);
302 void Parser::pop_back()
308 Token const & Parser::prevToken() const
310 static const Token dummy;
311 return pos_ > 0 ? tokens_[pos_ - 1] : dummy;
315 Token const & Parser::nextToken() const
317 static const Token dummy;
318 return good() ? tokens_[pos_] : dummy;
322 Token const & Parser::getToken()
324 static const Token dummy;
325 return good() ? tokens_[pos_++] : dummy;
329 void Parser::putback()
335 bool Parser::good() const
337 return pos_ < tokens_.size();
341 char Parser::getChar()
344 lyxerr << "The input stream is not well..." << endl;
345 return tokens_[pos_++].character();
349 string Parser::getArg(char lf, char rg)
357 while ((c = getChar()) != rg && good())
364 void Parser::tokenize(istream & is)
366 // eat everything up to the next \end_inset or end of stream
367 // and store it in s for further tokenization
372 if (s.size() >= 10 && s.substr(s.size() - 10) == "\\end_inset") {
373 s = s.substr(0, s.size() - 10);
383 void Parser::tokenize(string const & buffer)
385 static bool init_done = false;
392 istringstream is(buffer, ios::in || ios::binary);
397 switch (catcode(c)) {
401 if (catcode(c) == catNewline)
402 ; //push_back(Token("par"));
404 push_back(Token(' ',catSpace));
411 while (is.get(c) && catcode(c) != catNewline)
420 if (catcode(c) == catLetter) {
421 while (is.get(c) && catcode(c) == catLetter)
423 if (catcode(c) == catSpace)
424 while (is.get(c) && catcode(c) == catSpace)
433 push_back(Token(c, catcode(c)));
437 //lyxerr << "\nTokens: ";
438 //for (unsigned i = 0; i < tokens_.size(); ++i)
439 // lyxerr << tokens_[i];
444 void Parser::error(string const & msg)
446 lyxerr << "Line ~" << lineno_ << ": Math parse error: " << msg << endl;
450 void Parser::parse_lines(MathGridInset * p, bool numbered, bool outmost)
452 const int cols = p->ncols();
454 // save global variables
455 bool const saved_num = curr_num_;
456 string const saved_label = curr_label_;
458 for (int row = 0; true; ++row) {
459 // reset global variables
460 curr_num_ = numbered;
464 for (int col = 0; col < cols; ++col) {
465 //lyxerr << "reading cell " << row << " " << col << "\n";
466 parse_into(p->cell(col + row * cols), FLAG_BLOCK);
469 if (prevToken().cat() != catAlign) {
470 //lyxerr << "less cells read than normal in row/col: "
471 // << row << " " << col << "\n";
477 MathMatrixInset * m = static_cast<MathMatrixInset *>(p);
478 m->numbered(row, curr_num_);
479 m->label(row, curr_label_);
480 if (curr_skip_.size()) {
481 m->vskip(LyXLength(curr_skip_), row);
487 if (prevToken() != Token("\\")) {
488 //lyxerr << "no newline here\n";
495 // restore "global" variables
496 curr_num_ = saved_num;
497 curr_label_ = saved_label;
501 MathMacroTemplate * Parser::parse_macro()
503 while (nextToken().cat() == catSpace)
506 if (getToken().cs() != "newcommand") {
507 lyxerr << "\\newcommand expected\n";
511 if (getToken().cat() != catBegin) {
512 lyxerr << "'{' expected\n";
516 string name = getToken().cs();
518 if (getToken().cat() != catEnd) {
519 lyxerr << "'}' expected\n";
523 string arg = getArg('[', ']');
524 int narg = arg.empty() ? 0 : atoi(arg.c_str());
525 //lyxerr << "creating macro " << name << " with " << narg << "args\n";
526 MathMacroTemplate * p = new MathMacroTemplate(name, narg);
527 parse_into(p->cell(0), FLAG_BRACE | FLAG_BRACE_LAST);
532 MathMatrixInset * Parser::parse_normal()
534 Token const & t = getToken();
536 if (t.cat() == catMath || t.cs() == "(") {
537 MathMatrixInset * p = new MathMatrixInset(LM_OT_SIMPLE);
538 parse_into(p->cell(0), 0);
542 if (!t.cs().size()) {
543 lyxerr << "start of math expected, got '" << t << "'\n";
547 string const & cs = t.cs();
552 MathMatrixInset * p = new MathMatrixInset(LM_OT_EQUATION);
553 parse_into(p->cell(0), 0);
554 p->numbered(0, curr_num_);
555 p->label(0, curr_label_);
560 lyxerr << "'begin' of un-simple math expected, got '" << cs << "'\n";
564 string const name = getArg('{', '}');
566 if (name == "equation" || name == "equation*") {
567 curr_num_ = stared(name);
569 MathMatrixInset * p = new MathMatrixInset(LM_OT_EQUATION);
570 parse_into(p->cell(0), FLAG_END);
571 p->numbered(0, curr_num_);
572 p->label(0, curr_label_);
576 if (name == "eqnarray" || name == "eqnarray*") {
577 MathMatrixInset * p = new MathMatrixInset(LM_OT_EQNARRAY);
578 parse_lines(p, stared(name), true);
582 if (name == "align" || name == "align*") {
583 MathMatrixInset * p = new MathMatrixInset(LM_OT_ALIGN);
584 p->halign(getArg('{', '}'));
585 parse_lines(p, stared(name), true);
589 if (name == "alignat" || name == "alignat*") {
590 MathMatrixInset * p = new MathMatrixInset(LM_OT_ALIGNAT);
591 p->halign(getArg('{', '}'));
592 parse_lines(p, stared(name), true);
596 lyxerr[Debug::MATHED] << "1: unknown math environment: " << name << "\n";
601 latexkeys const * Parser::read_delim()
603 Token const & t = getToken();
604 latexkeys const * l = in_word_set(t.asString());
605 return l ? l : in_word_set(".");
609 void Parser::parse_into(MathArray & array, unsigned flags)
611 MathTextCodes yyvarcode = LM_TC_MIN;
617 Token const & t = getToken();
619 lyxerr << "t: " << t << " flags: " << flags << "'\n";
620 //array.dump(lyxerr);
623 if (flags & FLAG_ITEM) {
625 if (t.cat() == catBegin) {
626 // skip the brace and collect everything to the next matching
628 flags |= FLAG_BRACE_LAST;
631 // handle only this single token, leave the loop if done
636 if (flags & FLAG_BRACE) {
637 if (t.cat() != catBegin) {
638 error("Expected {. Maybe you forgot to enclose an argument in {}");
642 flags &= ~FLAG_BRACE;
647 if (flags & FLAG_BLOCK) {
648 if (t.cat() == catEnd || t.cat() == catAlign || t.cs() == "\\")
650 if (t.cs() == "end") {
659 if (t.cat() == catMath)
662 else if (t.cat() == catLetter)
663 array.push_back(new MathCharInset(t.character(), yyvarcode));
665 else if (t.cat() == catSpace && yyvarcode == LM_TC_TEXTRM)
666 array.push_back(new MathCharInset(' ', yyvarcode));
668 else if (t.cat() == catParameter) {
669 Token const & n = getToken();
670 MathMacroArgument * p = new MathMacroArgument(n.character() - '0');
674 else if (t.cat() == catBegin) {
675 //lyxerr << " creating ScopeInset\n";
676 array.push_back(new MathScopeInset);
677 parse_into(array.back()->cell(0), FLAG_BRACE_LAST);
680 else if (t.cat() == catEnd) {
681 if (!(flags & FLAG_BRACE_LAST))
682 lyxerr << " ##### unexpected end of block\n";
686 else if (t.cat() == catAlign) {
687 lyxerr << "found tab unexpectedly, array: '" << array << "'\n";
691 else if (t.cat() == catSuper)
692 parse_into(lastScriptInset(array, true, limits)->cell(0), FLAG_ITEM);
694 else if (t.cat() == catSub)
695 parse_into(lastScriptInset(array, false, limits)->cell(1), FLAG_ITEM);
697 else if (t.character() == ']' && (flags & FLAG_BRACK_END))
700 else if (t.cat() == catOther)
701 array.push_back(new MathCharInset(t.character(), yyvarcode));
706 else if (t.cs() == "protect")
709 else if (t.cs() == "end")
712 else if (t.cs() == ")")
715 else if (t.cs() == "]")
718 else if (t.cs() == "\\") {
719 curr_skip_ = getArg('[', ']');
720 if (!(flags & FLAG_NEWLINE))
721 lyxerr[Debug::MATHED]
722 << "found newline unexpectedly, array: '" << array << "'\n";
726 else if (t.cs() == "limits")
729 else if (t.cs() == "nolimits")
732 else if (t.cs() == "nonumber")
735 else if (t.cs() == "number")
738 else if (t.cs() == "sqrt") {
741 array.push_back(new MathRootInset);
742 parse_into(array.back()->cell(0), FLAG_BRACK_END);
743 parse_into(array.back()->cell(1), FLAG_ITEM);
746 array.push_back(new MathSqrtInset);
747 parse_into(array.back()->cell(0), FLAG_ITEM);
751 else if (t.cs() == "left") {
752 latexkeys const * l = read_delim();
754 parse_into(ar, FLAG_RIGHT);
755 latexkeys const * r = read_delim();
756 MathDelimInset * dl = new MathDelimInset(l, r);
761 else if (t.cs() == "right") {
762 if (!(flags & FLAG_RIGHT))
763 error("Unmatched right delimiter");
770 lyxerr[Debug::MATHED] << "LM_TK_STY not implemented\n";
771 //MathArray tmp = array;
772 //MathSizeInset * p = new MathSizeInset(MathStyles(lval_->id));
773 //array.push_back(p);
774 //parse_into(p->cell(0), FLAG_BRACE_FONT);
779 if (MathMacroTable::hasTemplate(sval_)) {
780 MathMacro * m = MathMacroTable::cloneTemplate(sval_);
781 for (int i = 0; i < m->nargs(); ++i)
782 parse_into(m->cell(i), FLAG_ITEM);
784 m->metrics(LM_ST_TEXT);
786 array.push_back(new MathFuncInset(sval_));
790 array.push_back(new MathCharInset(ival_, LM_TC_SPECIAL));
794 else if (t.cs() == "begin") {
795 string const name = getArg('{', '}');
796 if (name == "array") {
797 string const valign = getArg('[', ']') + 'c';
798 string const halign = getArg('{', '}');
799 MathArrayInset * m = new MathArrayInset(halign.size(), 1);
800 m->valign(valign[0]);
802 parse_lines(m, false, false);
805 lyxerr[Debug::MATHED] << "unknow math inset begin '" << name << "'\n";
808 else if (t.cs() == "label") {
810 parse_into(ar, FLAG_ITEM);
813 curr_label_ = os.str();
815 //curr_label_ = getArg('{', '}');
818 else if (t.cs() == "choose" || t.cs() == "over") {
820 MathInset * p = createMathInset(t.cs());
821 p->cell(0).swap(array);
823 parse_into(p->cell(1), FLAG_BLOCK);
826 else if (t.cs().size()) {
828 latexkeys const * l = in_word_set(t.cs());
830 if (l->token == LM_TK_FONT) {
831 //lyxerr << "starting font\n";
833 parse_into(ar, FLAG_ITEM);
834 for (MathArray::iterator it = ar.begin(); it != ar.end(); ++it)
835 (*it)->handleFont(static_cast<MathTextCodes>(l->id));
837 //lyxerr << "ending font\n";
840 else if (l->token == LM_TK_OLDFONT)
841 yyvarcode = static_cast<MathTextCodes>(l->id);
844 MathInset * p = createMathInset(t.cs());
845 for (int i = 0; i < p->nargs(); ++i)
846 parse_into(p->cell(i), FLAG_ITEM);
852 MathInset * p = createMathInset(t.cs());
854 for (int i = 0; i < p->nargs(); ++i)
855 parse_into(p->cell(i), FLAG_ITEM);
858 error("Unrecognized token");
859 //lyxerr[Debug::MATHED] << "[" << t << "]\n";
866 if (flags & FLAG_LEAVE) {
867 flags &= ~FLAG_LEAVE;
873 lyxerr << " Math Panic, expect problems!\n";
874 // Search for the end command.
878 } while (good() && t.cs() != "end");
882 } // anonymous namespace
886 MathArray mathed_parse_cell(string const & str)
888 istringstream is(str.c_str());
891 parser.parse_into(ar, 0);
897 MathMacroTemplate * mathed_parse_macro(string const & str)
899 istringstream is(str.c_str());
901 return parser.parse_macro();
904 MathMacroTemplate * mathed_parse_macro(istream & is)
907 return parser.parse_macro();
910 MathMacroTemplate * mathed_parse_macro(LyXLex & lex)
913 return parser.parse_macro();
918 MathMatrixInset * mathed_parse_normal(string const & str)
920 istringstream is(str.c_str());
922 return parser.parse_normal();
925 MathMatrixInset * mathed_parse_normal(istream & is)
928 return parser.parse_normal();
931 MathMatrixInset * mathed_parse_normal(LyXLex & lex)
934 return parser.parse_normal();