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] == '*';
64 MathScriptInset * prevScriptInset(MathArray const & array)
66 MathInset * p = array.back();
67 return (p && p->isScriptInset()) ? static_cast<MathScriptInset *>(p) : 0;
71 MathInset * lastScriptInset(MathArray & array, bool up, int limits)
73 MathScriptInset * p = prevScriptInset(array);
75 MathInset * b = array.back();
76 if (b && b->isScriptable()) {
77 p = new MathScriptInset(up, !up, b->clone());
80 p = new MathScriptInset(up, !up);
94 // These are TeX's catcodes
96 catEscape, // 0 backslash
106 catSpace, // 10 space
107 catLetter, // 11 a-zA-Z
108 catOther, // 12 none of the above
111 catInvalid // 15 <delete>
114 CatCode theCatcode[256];
117 inline CatCode catcode(unsigned char c)
119 return theCatcode[c];
124 FLAG_BRACE = 1 << 0, // an opening brace needed
125 FLAG_BRACE_LAST = 1 << 1, // last closing brace ends the parsing process
126 FLAG_RIGHT = 1 << 2, // next \\right ends the parsing process
127 FLAG_END = 1 << 3, // next \\end ends the parsing process
128 FLAG_BRACK_END = 1 << 4, // next closing bracket ends the parsing process
129 FLAG_NEWLINE = 1 << 6, // next \\\\ ends the parsing process
130 FLAG_ITEM = 1 << 7, // read a (possibly braced token)
131 FLAG_BLOCK = 1 << 8, // next block ends the parsing process
132 FLAG_LEAVE = 1 << 9 // leave the loop at the end
138 for (int i = 0; i <= 255; ++i)
139 theCatcode[i] = catOther;
140 for (int i = 'a'; i <= 'z'; ++i)
141 theCatcode[i] = catLetter;
142 for (int i = 'A'; i <= 'Z'; ++i)
143 theCatcode[i] = catLetter;
145 theCatcode['\\'] = catEscape;
146 theCatcode['{'] = catBegin;
147 theCatcode['}'] = catEnd;
148 theCatcode['$'] = catMath;
149 theCatcode['&'] = catAlign;
150 theCatcode['\n'] = catNewline;
151 theCatcode['#'] = catParameter;
152 theCatcode['^'] = catSuper;
153 theCatcode['_'] = catSub;
154 theCatcode['
\7f'] = catIgnore;
155 theCatcode[' '] = catSpace;
156 theCatcode['\t'] = catSpace;
157 theCatcode['\r'] = catSpace;
158 theCatcode['~'] = catActive;
159 theCatcode['%'] = catComment;
165 // Helper class for parsing
171 Token() : cs_(), char_(0), cat_(catIgnore) {}
173 Token(char c, CatCode cat) : cs_(), char_(c), cat_(cat) {}
175 Token(const string & cs) : cs_(cs), char_(0), cat_(catIgnore) {}
178 string const & cs() const { return cs_; }
180 CatCode cat() const { return cat_; }
182 char character() const { return char_; }
184 string asString() const;
195 string Token::asString() const
197 return cs_.size() ? cs_ : string(1, char_);
200 bool operator==(Token const & s, Token const & t)
202 return s.character() == t.character()
203 && s.cat() == t.cat() && s.cs() == t.cs();
206 bool operator!=(Token const & s, Token const & t)
211 ostream & operator<<(ostream & os, Token const & t)
214 os << "\\" << t.cs();
216 os << "[" << t.character() << "," << t.cat() << "]";
225 Parser(LyXLex & lex);
227 Parser(istream & is);
230 MathMacroTemplate * parse_macro();
232 MathMatrixInset * parse_normal();
234 void parse_into(MathArray & array, unsigned flags, MathTextCodes = LM_TC_MIN);
236 int lineno() const { return lineno_; }
242 string getArg(char lf, char rf);
246 void error(string const & msg);
248 void parse_lines(MathGridInset * p, bool numbered, bool outmost);
250 latexkeys const * read_delim();
254 void tokenize(istream & is);
256 void tokenize(string const & s);
258 void push_back(Token const & t);
262 Token const & prevToken() const;
264 Token const & nextToken() const;
266 Token const & getToken();
268 void lex(string const & s);
275 std::vector<Token> tokens_;
287 Parser::Parser(LyXLex & lexer)
288 : lineno_(lexer.getLineNo()), pos_(0), curr_num_(false)
290 tokenize(lexer.getStream());
295 Parser::Parser(istream & is)
296 : lineno_(0), pos_(0), curr_num_(false)
302 void Parser::push_back(Token const & t)
304 tokens_.push_back(t);
308 void Parser::pop_back()
314 Token const & Parser::prevToken() const
316 static const Token dummy;
317 return pos_ > 0 ? tokens_[pos_ - 1] : dummy;
321 Token const & Parser::nextToken() const
323 static const Token dummy;
324 return good() ? tokens_[pos_] : dummy;
328 Token const & Parser::getToken()
330 static const Token dummy;
331 return good() ? tokens_[pos_++] : dummy;
335 void Parser::putback()
341 bool Parser::good() const
343 return pos_ < tokens_.size();
347 char Parser::getChar()
350 lyxerr << "The input stream is not well..." << endl;
351 return tokens_[pos_++].character();
355 string Parser::getArg(char lf, char rg)
363 while ((c = getChar()) != rg && good())
370 void Parser::tokenize(istream & is)
372 // eat everything up to the next \end_inset or end of stream
373 // and store it in s for further tokenization
378 if (s.size() >= 10 && s.substr(s.size() - 10) == "\\end_inset") {
379 s = s.substr(0, s.size() - 10);
389 void Parser::tokenize(string const & buffer)
391 static bool init_done = false;
398 istringstream is(buffer, ios::in | ios::binary);
403 switch (catcode(c)) {
407 if (catcode(c) == catNewline)
408 ; //push_back(Token("par"));
410 push_back(Token(' ', catSpace));
417 while (is.get(c) && catcode(c) != catNewline)
426 if (catcode(c) == catLetter) {
427 while (is.get(c) && catcode(c) == catLetter)
429 if (catcode(c) == catSpace)
430 while (is.get(c) && catcode(c) == catSpace)
439 push_back(Token(c, catcode(c)));
444 lyxerr << "\nTokens: ";
445 for (unsigned i = 0; i < tokens_.size(); ++i)
446 lyxerr << tokens_[i];
452 void Parser::error(string const & msg)
454 lyxerr << "Line ~" << lineno_ << ": Math parse error: " << msg << endl;
458 void Parser::parse_lines(MathGridInset * p, bool numbered, bool outmost)
460 const int cols = p->ncols();
462 // save global variables
463 bool const saved_num = curr_num_;
464 string const saved_label = curr_label_;
466 for (int row = 0; true; ++row) {
467 // reset global variables
468 curr_num_ = numbered;
472 for (int col = 0; col < cols; ++col) {
473 //lyxerr << "reading cell " << row << " " << col << "\n";
474 parse_into(p->cell(col + row * cols), FLAG_BLOCK);
477 if (prevToken().cat() != catAlign) {
478 //lyxerr << "less cells read than normal in row/col: "
479 // << row << " " << col << "\n";
485 MathMatrixInset * m = static_cast<MathMatrixInset *>(p);
486 m->numbered(row, curr_num_);
487 m->label(row, curr_label_);
488 if (curr_skip_.size()) {
489 m->vskip(LyXLength(curr_skip_), row);
495 if (prevToken() != Token("\\")) {
496 //lyxerr << "no newline here\n";
503 // restore "global" variables
504 curr_num_ = saved_num;
505 curr_label_ = saved_label;
509 MathMacroTemplate * Parser::parse_macro()
511 while (nextToken().cat() == catSpace)
514 if (getToken().cs() != "newcommand") {
515 lyxerr << "\\newcommand expected\n";
519 if (getToken().cat() != catBegin) {
520 lyxerr << "'{' expected\n";
524 string name = getToken().cs();
526 if (getToken().cat() != catEnd) {
527 lyxerr << "'}' expected\n";
531 string arg = getArg('[', ']');
532 int narg = arg.empty() ? 0 : atoi(arg.c_str());
533 //lyxerr << "creating macro " << name << " with " << narg << "args\n";
534 MathMacroTemplate * p = new MathMacroTemplate(name, narg);
535 parse_into(p->cell(0), FLAG_BRACE | FLAG_BRACE_LAST);
540 MathMatrixInset * Parser::parse_normal()
542 while (nextToken().cat() == catSpace)
545 Token const & t = getToken();
547 if (t.cat() == catMath || t.cs() == "(") {
548 MathMatrixInset * p = new MathMatrixInset(LM_OT_SIMPLE);
549 parse_into(p->cell(0), 0);
553 if (!t.cs().size()) {
554 lyxerr << "start of math expected, got '" << t << "'\n";
558 string const & cs = t.cs();
563 MathMatrixInset * p = new MathMatrixInset(LM_OT_EQUATION);
564 parse_into(p->cell(0), 0);
565 p->numbered(0, curr_num_);
566 p->label(0, curr_label_);
571 lyxerr << "'begin' of un-simple math expected, got '" << cs << "'\n";
575 string const name = getArg('{', '}');
577 if (name == "equation" || name == "equation*") {
578 curr_num_ = !stared(name);
580 MathMatrixInset * p = new MathMatrixInset(LM_OT_EQUATION);
581 parse_into(p->cell(0), FLAG_END);
582 p->numbered(0, curr_num_);
583 p->label(0, curr_label_);
587 if (name == "eqnarray" || name == "eqnarray*") {
588 MathMatrixInset * p = new MathMatrixInset(LM_OT_EQNARRAY);
589 parse_lines(p, !stared(name), true);
593 if (name == "align" || name == "align*") {
594 MathMatrixInset * p = new MathMatrixInset(LM_OT_ALIGN);
595 parse_lines(p, !stared(name), true);
599 if (name == "alignat" || name == "alignat*") {
600 MathMatrixInset * p =
601 new MathMatrixInset(LM_OT_ALIGNAT, 2 * atoi(getArg('{', '}').c_str()));
602 parse_lines(p, !stared(name), true);
606 if (name == "xalignat" || name == "xalignat*") {
607 MathMatrixInset * p =
608 new MathMatrixInset(LM_OT_XALIGNAT, 2 * atoi(getArg('{', '}').c_str()));
609 parse_lines(p, !stared(name), true);
613 if (name == "xxalignat") {
614 MathMatrixInset * p =
615 new MathMatrixInset(LM_OT_XXALIGNAT, 2 * atoi(getArg('{', '}').c_str()));
616 parse_lines(p, !stared(name), true);
620 if (name == "multline" || name == "multline*") {
621 MathMatrixInset * p = new MathMatrixInset(LM_OT_MULTLINE);
622 parse_lines(p, !stared(name), true);
626 if (name == "gather" || name == "gather*") {
627 MathMatrixInset * p = new MathMatrixInset(LM_OT_GATHER);
628 parse_lines(p, !stared(name), true);
632 lyxerr[Debug::MATHED] << "1: unknown math environment: " << name << "\n";
637 latexkeys const * Parser::read_delim()
639 Token const & t = getToken();
640 latexkeys const * l = in_word_set(t.asString());
641 return l ? l : in_word_set(".");
645 void Parser::parse_into(MathArray & array, unsigned flags, MathTextCodes code)
647 MathTextCodes yyvarcode = LM_TC_MIN;
653 Token const & t = getToken();
655 //lyxerr << "t: " << t << " flags: " << flags << "'\n";
656 //array.dump(lyxerr);
659 if (flags & FLAG_ITEM) {
661 if (t.cat() == catBegin) {
662 // skip the brace and collect everything to the next matching
664 flags |= FLAG_BRACE_LAST;
667 // handle only this single token, leave the loop if done
672 if (flags & FLAG_BRACE) {
673 if (t.cat() != catBegin) {
674 error("Expected {. Maybe you forgot to enclose an argument in {}");
678 flags &= ~FLAG_BRACE;
683 if (flags & FLAG_BLOCK) {
684 if (t.cat() == catAlign || t.cs() == "\\")
686 if (t.cs() == "end") {
695 if (t.cat() == catMath)
698 else if (t.cat() == catLetter)
699 array.push_back(new MathCharInset(t.character(), yyvarcode));
701 else if (t.cat() == catSpace &&
702 (yyvarcode == LM_TC_TEXTRM || code == LM_TC_TEXTRM))
703 array.push_back(new MathCharInset(' ', yyvarcode));
705 else if (t.cat() == catParameter) {
706 Token const & n = getToken();
707 MathMacroArgument * p = new MathMacroArgument(n.character() - '0');
711 else if (t.cat() == catBegin) {
712 array.push_back(new MathCharInset('{', LM_TC_TEX));
715 else if (t.cat() == catEnd) {
716 if (flags & FLAG_BRACE_LAST)
718 array.push_back(new MathCharInset('}', LM_TC_TEX));
721 else if (t.cat() == catAlign) {
722 lyxerr << "found tab unexpectedly, array: '" << array << "'\n";
723 array.push_back(new MathCharInset('&', LM_TC_TEX));
726 else if (t.cat() == catSuper)
727 parse_into(lastScriptInset(array, true, limits)->cell(0), FLAG_ITEM);
729 else if (t.cat() == catSub)
730 parse_into(lastScriptInset(array, false, limits)->cell(1), FLAG_ITEM);
732 else if (t.character() == ']' && (flags & FLAG_BRACK_END))
735 else if (t.cat() == catOther)
736 array.push_back(new MathCharInset(t.character(), yyvarcode));
741 else if (t.cs() == "protect")
744 else if (t.cs() == "end")
747 else if (t.cs() == ")")
750 else if (t.cs() == "]")
753 else if (t.cs() == "\\") {
754 curr_skip_ = getArg('[', ']');
755 if (flags & FLAG_NEWLINE)
757 lyxerr[Debug::MATHED]
758 << "found newline unexpectedly, array: '" << array << "'\n";
759 array.push_back(createMathInset("\\"));
762 else if (t.cs() == "limits")
765 else if (t.cs() == "nolimits")
768 else if (t.cs() == "nonumber")
771 else if (t.cs() == "number")
774 else if (t.cs() == "sqrt") {
777 array.push_back(new MathRootInset);
778 parse_into(array.back()->cell(0), FLAG_BRACK_END);
779 parse_into(array.back()->cell(1), FLAG_ITEM);
782 array.push_back(new MathSqrtInset);
783 parse_into(array.back()->cell(0), FLAG_ITEM);
787 else if (t.cs() == "left") {
788 latexkeys const * l = read_delim();
790 parse_into(ar, FLAG_RIGHT);
791 latexkeys const * r = read_delim();
792 MathDelimInset * dl = new MathDelimInset(l, r);
797 else if (t.cs() == "right") {
798 if (!(flags & FLAG_RIGHT))
799 error("Unmatched right delimiter");
806 lyxerr[Debug::MATHED] << "LM_TK_STY not implemented\n";
807 //MathArray tmp = array;
808 //MathSizeInset * p = new MathSizeInset(MathStyles(lval_->id));
809 //array.push_back(p);
810 //parse_into(p->cell(0), FLAG_BRACE_FONT);
815 array.push_back(new MathCharInset(ival_, LM_TC_TEX));
819 else if (t.cs() == "begin") {
820 string const name = getArg('{', '}');
821 if (name == "array") {
822 string const valign = getArg('[', ']') + 'c';
823 string const halign = getArg('{', '}');
824 MathArrayInset * m = new MathArrayInset(halign.size(), 1);
825 m->valign(valign[0]);
827 parse_lines(m, false, false);
829 } else if (name == "split") {
830 MathSplitInset * m = new MathSplitInset(1);
831 parse_lines(m, false, false);
834 lyxerr[Debug::MATHED] << "unknow math inset begin '" << name << "'\n";
837 else if (t.cs() == "kern") {
843 Token const & t = getToken();
849 if (isValidLength(s))
852 array.push_back(new MathKernInset(s));
855 else if (t.cs() == "label") {
857 //parse_into(ar, FLAG_ITEM);
859 //ar.write(os, true);
860 //curr_label_ = os.str();
862 curr_label_ = getArg('{', '}');
865 else if (t.cs() == "choose" || t.cs() == "over" || t.cs() == "atop") {
867 MathInset * p = createMathInset(t.cs());
868 // search backward for position of last '{' if any
870 for (pos = array.size() - 1; pos >= 0; --pos) {
871 MathInset * q = array.nextInset(pos);
872 if (q->getChar() == '{')
876 // found it -> use the part after '{' as "numerator", erase the '{'
877 p->cell(0) = MathArray(array, pos + 1, array.size());
878 array.erase(pos, array.size());
880 // not found -> use everything as "numerator"
881 p->cell(0).swap(array);
884 parse_into(p->cell(1), FLAG_BLOCK);
887 else if (t.cs().size()) {
889 latexkeys const * l = in_word_set(t.cs());
891 if (l->token == LM_TK_FONT) {
892 //lyxerr << "starting font\n";
893 //CatCode catSpaceSave = theCatcode[' '];
894 //if (l->id == LM_TC_TEXTRM) {
895 // // temporarily change catcode
896 // theCatcode[' '] = catLetter;
899 MathTextCodes t = static_cast<MathTextCodes>(l->id);
901 parse_into(ar, FLAG_ITEM, t);
902 for (MathArray::iterator it = ar.begin(); it != ar.end(); ++it)
903 (*it)->handleFont(t);
906 // undo catcode changes
907 ////theCatcode[' '] = catSpaceSave;
908 //lyxerr << "ending font\n";
911 else if (l->token == LM_TK_OLDFONT)
912 yyvarcode = static_cast<MathTextCodes>(l->id);
915 MathInset * p = createMathInset(t.cs());
916 for (int i = 0; i < p->nargs(); ++i)
917 parse_into(p->cell(i), FLAG_ITEM);
923 MathInset * p = createMathInset(t.cs());
925 for (int i = 0; i < p->nargs(); ++i)
926 parse_into(p->cell(i), FLAG_ITEM);
929 error("Unrecognized token");
930 //lyxerr[Debug::MATHED] << "[" << t << "]\n";
937 if (flags & FLAG_LEAVE) {
938 flags &= ~FLAG_LEAVE;
944 lyxerr << " Math Panic, expect problems!\n";
945 // Search for the end command.
949 } while (good() && t.cs() != "end");
953 } // anonymous namespace
957 MathArray mathed_parse_cell(string const & str)
959 istringstream is(str.c_str());
962 parser.parse_into(ar, 0);
968 MathMacroTemplate * mathed_parse_macro(string const & str)
970 istringstream is(str.c_str());
972 return parser.parse_macro();
975 MathMacroTemplate * mathed_parse_macro(istream & is)
978 return parser.parse_macro();
981 MathMacroTemplate * mathed_parse_macro(LyXLex & lex)
984 return parser.parse_macro();
989 MathMatrixInset * mathed_parse_normal(string const & str)
991 istringstream is(str.c_str());
993 return parser.parse_normal();
996 MathMatrixInset * mathed_parse_normal(istream & is)
999 return parser.parse_normal();
1002 MathMatrixInset * mathed_parse_normal(LyXLex & lex)
1005 return parser.parse_normal();