3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
8 * Full author contact details are available in file CREDITS.
13 If someone desperately needs partial "structures" (such as a few
14 cells of an array inset or similar) (s)he could uses the
15 following hack as starting point to write some macros:
20 \def\makeamptab{\catcode`\&=4\relax}
21 \def\makeampletter{\catcode`\&=11\relax}
22 \def\b{\makeampletter\expandafter\makeamptab\bi}
40 #include "MathParser.h"
42 #include "InsetMathArray.h"
43 #include "InsetMathBig.h"
44 #include "InsetMathBrace.h"
45 #include "InsetMathChar.h"
46 #include "InsetMathColor.h"
47 #include "InsetMathComment.h"
48 #include "InsetMathDelim.h"
49 #include "InsetMathEnv.h"
50 #include "InsetMathFrac.h"
51 #include "InsetMathKern.h"
52 #include "MathMacro.h"
53 #include "InsetMathPar.h"
54 #include "InsetMathRef.h"
55 #include "InsetMathRoot.h"
56 #include "InsetMathScript.h"
57 #include "InsetMathSplit.h"
58 #include "InsetMathSqrt.h"
59 #include "InsetMathTabular.h"
60 #include "MathMacroTemplate.h"
61 #include "MathFactory.h"
62 #include "MathMacroArgument.h"
63 #include "MathSupport.h"
68 #include "support/debug.h"
69 #include "support/convert.h"
70 #include "support/docstream.h"
71 #include "support/lstrings.h"
85 InsetMath::mode_type asMode(InsetMath::mode_type oldmode, docstring const & str)
87 //lyxerr << "handling mode: '" << str << "'" << endl;
88 if (str == "mathmode")
89 return InsetMath::MATH_MODE;
90 if (str == "textmode" || str == "forcetext")
91 return InsetMath::TEXT_MODE;
96 bool stared(docstring const & s)
98 size_t const n = s.size();
99 return n && s[n - 1] == '*';
103 docstring escapeSpecialChars(docstring const & str, bool textmode)
105 docstring const backslash = textmode ? from_ascii("\\textbackslash ")
106 : from_ascii("\\backslash ");
107 docstring const caret = textmode ? from_ascii("\\textasciicircum ")
108 : from_ascii("\\mathcircumflex ");
110 return subst(subst(subst(subst(subst(subst(subst(subst(subst(str,
111 from_ascii("\\"), backslash),
112 from_ascii("^"), caret),
113 from_ascii("_"), from_ascii("\\_")),
114 from_ascii("$"), from_ascii("\\$")),
115 from_ascii("#"), from_ascii("\\#")),
116 from_ascii("&"), from_ascii("\\&")),
117 from_ascii("%"), from_ascii("\\%")),
118 from_ascii("{"), from_ascii("\\{")),
119 from_ascii("}"), from_ascii("\\}"));
124 * Add the row \p cellrow to \p grid.
125 * \returns wether the row could be added. Adding a row can fail for
126 * environments like "equation" that have a fixed number of rows.
128 bool addRow(InsetMathGrid & grid, InsetMathGrid::row_type & cellrow,
129 docstring const & vskip, bool allow_newpage_ = true)
132 if (cellrow == grid.nrows()) {
133 //lyxerr << "adding row " << cellrow << endl;
134 grid.addRow(cellrow - 1);
135 if (cellrow == grid.nrows()) {
136 // We can't add a row to this grid, so let's
137 // append the content of this cell to the previous
139 // This does not happen in well formed .lyx files,
140 // but LyX versions 1.3.x and older could create
141 // such files and tex2lyx can still do that.
143 lyxerr << "ignoring extra row";
145 lyxerr << " with extra space " << to_utf8(vskip);
147 lyxerr << " with no page break allowed";
148 lyxerr << '.' << endl;
152 grid.vcrskip(Length(to_utf8(vskip)), cellrow - 1);
153 grid.rowinfo(cellrow - 1).allow_newpage_ = allow_newpage_;
159 * Add the column \p cellcol to \p grid.
160 * \returns wether the column could be added. Adding a column can fail for
161 * environments like "eqnarray" that have a fixed number of columns.
163 bool addCol(InsetMathGrid & grid, InsetMathGrid::col_type & cellcol)
166 if (cellcol == grid.ncols()) {
167 //lyxerr << "adding column " << cellcol << endl;
168 grid.addCol(cellcol);
169 if (cellcol == grid.ncols()) {
170 // We can't add a column to this grid, so let's
171 // append the content of this cell to the previous
173 // This does not happen in well formed .lyx files,
174 // but LyX versions 1.3.x and older could create
175 // such files and tex2lyx can still do that.
177 lyxerr << "ignoring extra column." << endl;
186 * Check wether the last row is empty and remove it if yes.
187 * Otherwise the following code
195 * will result in a grid with 3 rows (+ the dummy row that is always present),
196 * because the last '\\' opens a new row.
198 void delEmptyLastRow(InsetMathGrid & grid)
200 InsetMathGrid::row_type const row = grid.nrows() - 1;
201 for (InsetMathGrid::col_type col = 0; col < grid.ncols(); ++col) {
202 if (!grid.cell(grid.index(row, col)).empty())
205 // Copy the row information of the empty row (which would contain the
206 // last hline in the example above) to the dummy row and delete the
208 grid.rowinfo(row + 1) = grid.rowinfo(row);
213 // These are TeX's catcodes
215 catEscape, // 0 backslash
225 catSpace, // 10 space
226 catLetter, // 11 a-zA-Z
227 catOther, // 12 none of the above
230 catInvalid // 15 <delete>
233 CatCode theCatcode[128];
236 inline CatCode catcode(char_type c)
238 /* The only characters that are not catOther lie in the pure ASCII
239 * range. Therefore theCatcode has only 128 entries.
240 * TeX itself deals with 8bit characters, so if needed this table
241 * could be enlarged to 256 entries.
242 * Any larger value does not make sense, since the fact that we use
243 * unicode internally does not change Knuth's TeX engine.
244 * Apart from that a table for the full 21bit UCS4 range would waste
245 * too much memory. */
249 return theCatcode[c];
254 FLAG_ALIGN = 1 << 0, // next & or \\ ends the parsing process
255 FLAG_BRACE_LAST = 1 << 1, // next closing brace ends the parsing
256 FLAG_RIGHT = 1 << 2, // next \\right ends the parsing process
257 FLAG_END = 1 << 3, // next \\end ends the parsing process
258 FLAG_BRACK_LAST = 1 << 4, // next closing bracket ends the parsing
259 FLAG_TEXTMODE = 1 << 5, // we are in a box
260 FLAG_ITEM = 1 << 6, // read a (possibly braced) token
261 FLAG_LEAVE = 1 << 7, // leave the loop at the end
262 FLAG_SIMPLE = 1 << 8, // next $ leaves the loop
263 FLAG_EQUATION = 1 << 9, // next \] leaves the loop
264 FLAG_SIMPLE2 = 1 << 10, // next \) leaves the loop
265 FLAG_OPTION = 1 << 11, // read [...] style option
266 FLAG_BRACED = 1 << 12 // read {...} style argument
271 // Helper class for parsing
277 Token() : cs_(), char_(0), cat_(catIgnore) {}
279 Token(char_type c, CatCode cat) : cs_(), char_(c), cat_(cat) {}
281 explicit Token(docstring const & cs) : cs_(cs), char_(0), cat_(catIgnore) {}
284 docstring const & cs() const { return cs_; }
286 CatCode cat() const { return cat_; }
288 char_type character() const { return char_; }
290 docstring asString() const { return cs_.size() ? cs_ : docstring(1, char_); }
292 docstring asInput() const { return cs_.size() ? '\\' + cs_ : docstring(1, char_); }
304 ostream & operator<<(ostream & os, Token const & t)
307 docstring const & cs = t.cs();
308 // FIXME: For some strange reason, the stream operator instanciate
309 // a new Token before outputting the contents of t.cs().
310 // Because of this the line
312 // below becomes recursive.
313 // In order to avoid that we return early:
316 os << '\\' << to_utf8(cs);
318 else if (t.cat() == catLetter)
321 os << '[' << t.character() << ',' << t.cat() << ']';
329 typedef InsetMath::mode_type mode_type;
331 typedef Parse::flags parse_mode;
334 Parser(Lexer & lex, parse_mode mode);
335 /// Only use this for reading from .lyx file format, for the reason
336 /// see Parser::tokenize(istream &).
337 Parser(istream & is, parse_mode mode);
339 Parser(docstring const & str, parse_mode mode);
342 bool parse(MathAtom & at);
344 bool parse(MathData & array, unsigned flags, mode_type mode);
346 bool parse1(InsetMathGrid & grid, unsigned flags, mode_type mode,
349 MathData parse(unsigned flags, mode_type mode);
351 int lineno() const { return lineno_; }
357 void parse2(MathAtom & at, unsigned flags, mode_type mode, bool numbered);
358 /// get arg delimited by 'left' and 'right'
359 docstring getArg(char_type left, char_type right);
363 void error(string const & msg);
364 void error(docstring const & msg) { error(to_utf8(msg)); }
365 /// dump contents to screen
367 /// Only use this for reading from .lyx file format (see
368 /// implementation for reason)
369 void tokenize(istream & is);
371 void tokenize(docstring const & s);
373 void skipSpaceTokens(idocstream & is, char_type c);
375 void push_back(Token const & t);
379 Token const & prevToken() const;
381 Token const & nextToken() const;
383 Token const & getToken();
384 /// skips spaces if any
387 void lex(docstring const & s);
391 docstring parse_verbatim_item();
393 docstring parse_verbatim_option();
398 vector<Token> tokens_;
401 /// Stack of active environments
402 vector<docstring> environments_;
410 Parser::Parser(Lexer & lexer, parse_mode mode)
411 : lineno_(lexer.lineNumber()), pos_(0), mode_(mode), success_(true)
413 tokenize(lexer.getStream());
418 Parser::Parser(istream & is, parse_mode mode)
419 : lineno_(0), pos_(0), mode_(mode), success_(true)
425 Parser::Parser(docstring const & str, parse_mode mode)
426 : lineno_(0), pos_(0), mode_(mode), success_(true)
432 void Parser::push_back(Token const & t)
434 tokens_.push_back(t);
438 void Parser::pop_back()
444 Token const & Parser::prevToken() const
446 static const Token dummy;
447 return pos_ > 0 ? tokens_[pos_ - 1] : dummy;
451 Token const & Parser::nextToken() const
453 static const Token dummy;
454 return good() ? tokens_[pos_] : dummy;
458 Token const & Parser::getToken()
460 static const Token dummy;
461 //lyxerr << "looking at token " << tokens_[pos_] << " pos: " << pos_ << endl;
462 return good() ? tokens_[pos_++] : dummy;
466 void Parser::skipSpaces()
468 while (nextToken().cat() == catSpace || nextToken().cat() == catNewline)
473 void Parser::putback()
479 bool Parser::good() const
481 return pos_ < tokens_.size();
485 char_type Parser::getChar()
488 error("The input stream is not well...");
492 return tokens_[pos_++].character();
496 docstring Parser::getArg(char_type left, char_type right)
501 char_type c = getChar();
506 while ((c = getChar()) != right && good())
513 void Parser::skipSpaceTokens(idocstream & is, char_type c)
515 // skip trailing spaces
516 while (catcode(c) == catSpace || catcode(c) == catNewline)
519 //lyxerr << "putting back: " << c << endl;
524 void Parser::tokenize(istream & is)
526 // eat everything up to the next \end_inset or end of stream
527 // and store it in s for further tokenization
532 if (s.size() >= 10 && s.substr(s.size() - 10) == "\\end_inset") {
533 s = s.substr(0, s.size() - 10);
537 // Remove the space after \end_inset
538 if (is.get(c) && c != ' ')
542 tokenize(from_utf8(s));
546 void Parser::tokenize(docstring const & buffer)
548 idocstringstream is(mode_ & Parse::VERBATIM
549 ? escapeSpecialChars(buffer, mode_ & Parse::TEXTMODE)
550 : buffer, ios::in | ios::binary);
554 //lyxerr << "reading c: " << c << endl;
556 switch (catcode(c)) {
560 if (catcode(c) == catNewline)
561 ; //push_back(Token("par"));
563 push_back(Token('\n', catNewline));
571 while (is.get(c) && catcode(c) != catNewline)
581 error("unexpected end of input");
584 if (catcode(c) == catLetter) {
586 while (is.get(c) && catcode(c) == catLetter)
588 skipSpaceTokens(is, c);
597 push_back(Token(c, catcode(c)));
599 skipSpaceTokens(is, c);
604 if (!(mode_ & Parse::QUIET))
605 lyxerr << "ignoring a char: " << int(c) << endl;
610 push_back(Token(c, catcode(c)));
620 void Parser::dump() const
622 lyxerr << "\nTokens: ";
623 for (unsigned i = 0; i < tokens_.size(); ++i) {
626 lyxerr << tokens_[i];
628 lyxerr << " pos: " << pos_ << endl;
632 void Parser::error(string const & msg)
635 if (!(mode_ & Parse::QUIET)) {
636 lyxerr << "Line ~" << lineno_ << ": Math parse error: "
643 bool Parser::parse(MathAtom & at)
647 parse(ar, false, InsetMath::UNDECIDED_MODE);
648 if (ar.size() != 1 || ar.front()->getType() == hullNone) {
649 if (!(mode_ & Parse::QUIET))
650 lyxerr << "unusual contents found: " << ar << endl;
651 at = MathAtom(new InsetMathPar(ar));
652 //if (at->nargs() > 0)
653 // at.nucleus()->cell(0) = ar;
655 // lyxerr << "unusual contents found: " << ar << endl;
663 docstring Parser::parse_verbatim_option()
667 if (nextToken().character() == '[') {
668 Token t = getToken();
669 for (Token t = getToken(); t.character() != ']' && good(); t = getToken()) {
670 if (t.cat() == catBegin) {
672 res += '{' + parse_verbatim_item() + '}';
681 docstring Parser::parse_verbatim_item()
685 if (nextToken().cat() == catBegin) {
686 Token t = getToken();
687 for (Token t = getToken(); t.cat() != catEnd && good(); t = getToken()) {
688 if (t.cat() == catBegin) {
690 res += '{' + parse_verbatim_item() + '}';
700 MathData Parser::parse(unsigned flags, mode_type mode)
703 parse(ar, flags, mode);
708 bool Parser::parse(MathData & array, unsigned flags, mode_type mode)
710 InsetMathGrid grid(1, 1);
711 parse1(grid, flags, mode, false);
712 array = grid.cell(0);
717 void Parser::parse2(MathAtom & at, const unsigned flags, const mode_type mode,
720 parse1(*(at.nucleus()->asGridInset()), flags, mode, numbered);
724 bool Parser::parse1(InsetMathGrid & grid, unsigned flags,
725 const mode_type mode, const bool numbered)
728 InsetMathGrid::row_type cellrow = 0;
729 InsetMathGrid::col_type cellcol = 0;
730 MathData * cell = &grid.cell(grid.index(cellrow, cellcol));
732 if (grid.asHullInset())
733 grid.asHullInset()->numbered(cellrow, numbered);
736 //lyxerr << " flags: " << flags << endl;
737 //lyxerr << " mode: " << mode << endl;
738 //lyxerr << "grid: " << grid << endl;
741 Token const & t = getToken();
744 lyxerr << "t: " << t << " flags: " << flags << endl;
745 lyxerr << "mode: " << mode << endl;
750 if (flags & FLAG_ITEM) {
752 if (t.cat() == catBegin) {
753 // skip the brace and collect everything to the next matching
755 parse1(grid, FLAG_BRACE_LAST, mode, numbered);
759 // handle only this single token, leave the loop if done
764 if (flags & FLAG_BRACED) {
765 if (t.cat() == catSpace)
768 if (t.cat() != catBegin) {
769 error("opening brace expected");
773 // skip the brace and collect everything to the next matching
775 flags = FLAG_BRACE_LAST;
779 if (flags & FLAG_OPTION) {
780 if (t.cat() == catOther && t.character() == '[') {
782 parse(ar, FLAG_BRACK_LAST, mode);
785 // no option found, put back token and we are done
794 if (t.cat() == catMath) {
795 if (mode != InsetMath::MATH_MODE) {
796 // we are inside some text mode thingy, so opening new math is allowed
797 Token const & n = getToken();
798 if (n.cat() == catMath) {
799 // TeX's $$...$$ syntax for displayed math
800 cell->push_back(MathAtom(new InsetMathHull(hullEquation)));
801 parse2(cell->back(), FLAG_SIMPLE, InsetMath::MATH_MODE, false);
802 getToken(); // skip the second '$' token
804 // simple $...$ stuff
806 cell->push_back(MathAtom(new InsetMathHull(hullSimple)));
807 parse2(cell->back(), FLAG_SIMPLE, InsetMath::MATH_MODE, false);
811 else if (flags & FLAG_SIMPLE) {
812 // this is the end of the formula
817 error("something strange in the parser");
822 else if (t.cat() == catLetter)
823 cell->push_back(MathAtom(new InsetMathChar(t.character())));
825 else if (t.cat() == catSpace && mode != InsetMath::MATH_MODE) {
826 if (cell->empty() || cell->back()->getChar() != ' ')
827 cell->push_back(MathAtom(new InsetMathChar(t.character())));
830 else if (t.cat() == catNewline && mode != InsetMath::MATH_MODE) {
831 if (cell->empty() || cell->back()->getChar() != ' ')
832 cell->push_back(MathAtom(new InsetMathChar(' ')));
835 else if (t.cat() == catParameter) {
836 Token const & n = getToken();
837 cell->push_back(MathAtom(new MathMacroArgument(n.character()-'0')));
840 else if (t.cat() == catActive)
841 cell->push_back(MathAtom(new InsetMathChar(t.character())));
843 else if (t.cat() == catBegin) {
845 parse(ar, FLAG_BRACE_LAST, mode);
846 // do not create a BraceInset if they were written by LyX
847 // this helps to keep the annoyance of "a choose b" to a minimum
848 if (ar.size() == 1 && ar[0]->extraBraces())
851 cell->push_back(MathAtom(new InsetMathBrace(ar)));
854 else if (t.cat() == catEnd) {
855 if (flags & FLAG_BRACE_LAST)
857 error("found '}' unexpectedly");
858 //LASSERT(false, /**/);
859 //add(cell, '}', LM_TC_TEX);
862 else if (t.cat() == catAlign) {
863 //lyxerr << " column now " << (cellcol + 1)
864 // << " max: " << grid.ncols() << endl;
865 if (flags & FLAG_ALIGN)
867 if (addCol(grid, cellcol))
868 cell = &grid.cell(grid.index(cellrow, cellcol));
871 else if (t.cat() == catSuper || t.cat() == catSub) {
872 bool up = (t.cat() == catSuper);
873 // we need no new script inset if the last thing was a scriptinset,
874 // which has that script already not the same script already
876 cell->push_back(MathAtom(new InsetMathScript(up)));
877 else if (cell->back()->asScriptInset() &&
878 !cell->back()->asScriptInset()->has(up))
879 cell->back().nucleus()->asScriptInset()->ensure(up);
880 else if (cell->back()->asScriptInset())
881 cell->push_back(MathAtom(new InsetMathScript(up)));
883 cell->back() = MathAtom(new InsetMathScript(cell->back(), up));
884 InsetMathScript * p = cell->back().nucleus()->asScriptInset();
885 // special handling of {}-bases
886 // Here we could remove the brace inset for things
887 // like {a'}^2 and add the braces back in
888 // InsetMathScript::write().
889 // We do not do it, since it is not possible to detect
890 // reliably whether the braces are needed because the
891 // nucleus contains more than one symbol, or whether
892 // they are needed for unknown commands like \xx{a}_0
893 // or \yy{a}{b}_0. This was done in revision 14819
894 // in an unreliable way. See this thread
895 // http://www.mail-archive.com/lyx-devel%40lists.lyx.org/msg104917.html
897 parse(p->cell(p->idxOfScript(up)), FLAG_ITEM, mode);
904 else if (t.character() == ']' && (flags & FLAG_BRACK_LAST)) {
905 //lyxerr << "finished reading option" << endl;
909 else if (t.cat() == catOther)
910 cell->push_back(MathAtom(new InsetMathChar(t.character())));
912 else if (t.cat() == catComment) {
915 Token const & t = getToken();
916 if (t.cat() == catNewline)
920 cell->push_back(MathAtom(new InsetMathComment(s)));
928 else if (t.cs() == "lyxlock") {
930 cell->back().nucleus()->lock(true);
933 else if ((t.cs() == "global" && nextToken().cs() == "def") ||
935 if (t.cs() == "global")
939 docstring name = getToken().cs();
944 while (good() && nextToken().cat() != catBegin) {
945 pars += getToken().cs();
952 parse(def, FLAG_ITEM, InsetMath::UNDECIDED_MODE);
954 // is a version for display attached?
957 if (nextToken().cat() == catBegin)
958 parse(display, FLAG_ITEM, InsetMath::MATH_MODE);
960 cell->push_back(MathAtom(new MathMacroTemplate(name, nargs,
961 0, MacroTypeDef, vector<MathData>(), def, display)));
964 else if (t.cs() == "newcommand" ||
965 t.cs() == "renewcommand" ||
966 t.cs() == "newlyxcommand") {
968 if (getToken().cat() != catBegin) {
969 error("'{' in \\newcommand expected (1) ");
972 docstring name = getToken().cs();
973 if (getToken().cat() != catEnd) {
974 error("'}' in \\newcommand expected");
979 docstring const arg = getArg('[', ']');
982 nargs = convert<int>(arg);
984 // optional argument given?
987 vector<MathData> optionalValues;
988 while (nextToken().character() == '[') {
990 optionalValues.push_back(MathData());
991 parse(optionalValues[optionals], FLAG_BRACK_LAST, mode);
996 parse(def, FLAG_ITEM, InsetMath::UNDECIDED_MODE);
998 // is a version for display attached?
1001 if (nextToken().cat() == catBegin)
1002 parse(display, FLAG_ITEM, InsetMath::MATH_MODE);
1004 cell->push_back(MathAtom(new MathMacroTemplate(name, nargs,
1005 optionals, MacroTypeNewcommand, optionalValues, def, display)));
1009 else if (t.cs() == "newcommandx" ||
1010 t.cs() == "renewcommandx") {
1011 // \newcommandx{\foo}[2][usedefault, addprefix=\global,1=default]{#1,#2}
1014 if (nextToken().cat() == catBegin) {
1016 name = getToken().cs();
1017 if (getToken().cat() != catEnd) {
1018 error("'}' in \\newcommandx expected");
1022 name = getToken().cs();
1025 docstring const arg = getArg('[', ']');
1027 error("[num] in \\newcommandx expected");
1030 int nargs = convert<int>(arg);
1034 vector<MathData> optionalValues;
1035 if (nextToken().character() == '[') {
1039 // handle 'opt=value' options, separated by ','.
1041 while (nextToken().character() != ']' && good()) {
1042 if (nextToken().character() >= '1'
1043 && nextToken().character() <= '9') {
1044 // optional value -> get parameter number
1045 int n = getChar() - '0';
1047 error("Arity of \\newcommandx too low "
1048 "for given optional parameter.");
1053 if (getToken().character() != '=') {
1054 error("'=' and optional parameter value "
1055 "expected for \\newcommandx");
1060 int optNum = max(size_t(n), optionalValues.size());
1061 optionalValues.resize(optNum);
1062 optionalValues[n - 1].clear();
1063 while (nextToken().character() != ']'
1064 && nextToken().character() != ',') {
1066 parse(data, FLAG_ITEM, InsetMath::UNDECIDED_MODE);
1067 optionalValues[n - 1].append(data);
1069 optionals = max(n, optionals);
1070 } else if (nextToken().cat() == catLetter) {
1071 // we in fact ignore every non-optional
1076 while (nextToken().cat() == catLetter)
1082 if (nextToken().character() == '=') {
1084 while (nextToken().character() != ']'
1085 && nextToken().character() != ',')
1086 parse(value, FLAG_ITEM,
1087 InsetMath::UNDECIDED_MODE);
1090 error("option for \\newcommandx expected");
1096 if (nextToken().character() == ',') {
1099 } else if (nextToken().character() != ']') {
1100 error("Expecting ',' or ']' in options "
1101 "of \\newcommandx");
1114 parse(def, FLAG_ITEM, InsetMath::UNDECIDED_MODE);
1116 // is a version for display attached?
1119 if (nextToken().cat() == catBegin)
1120 parse(display, FLAG_ITEM, InsetMath::MATH_MODE);
1122 cell->push_back(MathAtom(new MathMacroTemplate(name, nargs,
1123 optionals, MacroTypeNewcommandx, optionalValues, def,
1127 else if (t.cs() == "(") {
1128 cell->push_back(MathAtom(new InsetMathHull(hullSimple)));
1129 parse2(cell->back(), FLAG_SIMPLE2, InsetMath::MATH_MODE, false);
1132 else if (t.cs() == "[") {
1133 cell->push_back(MathAtom(new InsetMathHull(hullEquation)));
1134 parse2(cell->back(), FLAG_EQUATION, InsetMath::MATH_MODE, false);
1137 else if (t.cs() == "protect")
1138 // ignore \\protect, will hopefully be re-added during output
1141 else if (t.cs() == "end") {
1142 if (flags & FLAG_END) {
1143 // eat environment name
1144 docstring const name = getArg('{', '}');
1145 if (environments_.empty())
1146 error("'found \\end{" + name +
1147 "}' without matching '\\begin{" +
1149 else if (name != environments_.back())
1150 error("'\\end{" + name +
1151 "}' does not match '\\begin{" +
1152 environments_.back() + "}'");
1154 environments_.pop_back();
1155 // Delete empty last row in matrix
1157 // If you abuse InsetMathGrid for
1158 // non-matrix like structures you
1159 // probably need to refine this test.
1160 // Right now we only have to test for
1161 // single line hull insets.
1162 if (grid.nrows() > 1)
1163 delEmptyLastRow(grid);
1167 error("found 'end' unexpectedly");
1170 else if (t.cs() == ")") {
1171 if (flags & FLAG_SIMPLE2)
1173 error("found '\\)' unexpectedly");
1176 else if (t.cs() == "]") {
1177 if (flags & FLAG_EQUATION)
1179 error("found '\\]' unexpectedly");
1182 else if (t.cs() == "\\") {
1183 if (flags & FLAG_ALIGN)
1186 if (nextToken().asInput() == "*") {
1188 added = addRow(grid, cellrow, docstring(), false);
1190 added = addRow(grid, cellrow, getArg('[', ']'));
1192 error("missing token after \\\\");
1195 if (grid.asHullInset())
1196 grid.asHullInset()->numbered(
1198 cell = &grid.cell(grid.index(cellrow,
1204 else if (t.cs() == "multicolumn") {
1205 // extract column count and insert dummy cells
1207 parse(count, FLAG_ITEM, mode);
1209 if (!extractNumber(count, cols)) {
1211 lyxerr << " can't extract number of cells from " << count << endl;
1213 // resize the table if necessary
1214 for (int i = 0; i < cols; ++i) {
1215 if (addCol(grid, cellcol)) {
1216 cell = &grid.cell(grid.index(
1218 // mark this as dummy
1219 grid.cellinfo(grid.index(
1220 cellrow, cellcol)).dummy_ = true;
1223 // the last cell is the real thing, not a dummy
1224 grid.cellinfo(grid.index(cellrow, cellcol)).dummy_ = false;
1226 // read special alignment
1228 parse(align, FLAG_ITEM, mode);
1229 //grid.cellinfo(grid.index(cellrow, cellcol)).align_ = extractString(align);
1231 // parse the remaining contents into the "real" cell
1232 parse(*cell, FLAG_ITEM, mode);
1236 else if (t.cs() == "limits")
1239 else if (t.cs() == "nolimits")
1242 else if (t.cs() == "nonumber") {
1243 if (grid.asHullInset())
1244 grid.asHullInset()->numbered(cellrow, false);
1247 else if (t.cs() == "number") {
1248 if (grid.asHullInset())
1249 grid.asHullInset()->numbered(cellrow, true);
1252 else if (t.cs() == "hline") {
1253 grid.rowinfo(cellrow).lines_ ++;
1256 else if (t.cs() == "sqrt") {
1258 parse(ar, FLAG_OPTION, mode);
1260 cell->push_back(MathAtom(new InsetMathRoot));
1261 cell->back().nucleus()->cell(0) = ar;
1262 parse(cell->back().nucleus()->cell(1), FLAG_ITEM, mode);
1264 cell->push_back(MathAtom(new InsetMathSqrt));
1265 parse(cell->back().nucleus()->cell(0), FLAG_ITEM, mode);
1269 else if (t.cs() == "unit") {
1270 // Allowed formats \unit[val]{unit}
1272 parse(ar, FLAG_OPTION, mode);
1274 cell->push_back(MathAtom(new InsetMathFrac(InsetMathFrac::UNIT)));
1275 cell->back().nucleus()->cell(0) = ar;
1276 parse(cell->back().nucleus()->cell(1), FLAG_ITEM, mode);
1278 cell->push_back(MathAtom(new InsetMathFrac(InsetMathFrac::UNIT, 1)));
1279 parse(cell->back().nucleus()->cell(0), FLAG_ITEM, mode);
1282 else if (t.cs() == "unitfrac") {
1283 // Here allowed formats are \unitfrac[val]{num}{denom}
1285 parse(ar, FLAG_OPTION, mode);
1287 cell->push_back(MathAtom(new InsetMathFrac(InsetMathFrac::UNITFRAC, 3)));
1288 cell->back().nucleus()->cell(2) = ar;
1290 cell->push_back(MathAtom(new InsetMathFrac(InsetMathFrac::UNITFRAC)));
1292 parse(cell->back().nucleus()->cell(0), FLAG_ITEM, mode);
1293 parse(cell->back().nucleus()->cell(1), FLAG_ITEM, mode);
1296 else if (t.cs() == "xrightarrow" || t.cs() == "xleftarrow") {
1297 cell->push_back(createInsetMath(t.cs()));
1298 parse(cell->back().nucleus()->cell(1), FLAG_OPTION, mode);
1299 parse(cell->back().nucleus()->cell(0), FLAG_ITEM, mode);
1302 else if (t.cs() == "ref" || t.cs() == "eqref" || t.cs() == "prettyref"
1303 || t.cs() == "pageref" || t.cs() == "vpageref" || t.cs() == "vref") {
1304 cell->push_back(MathAtom(new InsetMathRef(t.cs())));
1305 parse(cell->back().nucleus()->cell(1), FLAG_OPTION, mode);
1306 parse(cell->back().nucleus()->cell(0), FLAG_ITEM, mode);
1309 else if (t.cs() == "left") {
1311 Token const & tl = getToken();
1312 // \| and \Vert are equivalent, and InsetMathDelim
1314 // FIXME: fix this in InsetMathDelim itself!
1315 docstring const l = tl.cs() == "|" ? from_ascii("Vert") : tl.asString();
1317 parse(ar, FLAG_RIGHT, mode);
1321 Token const & tr = getToken();
1322 docstring const r = tr.cs() == "|" ? from_ascii("Vert") : tr.asString();
1323 cell->push_back(MathAtom(new InsetMathDelim(l, r, ar)));
1326 else if (t.cs() == "right") {
1327 if (flags & FLAG_RIGHT)
1329 //lyxerr << "got so far: '" << cell << "'" << endl;
1330 error("Unmatched right delimiter");
1334 else if (t.cs() == "begin") {
1335 docstring const name = getArg('{', '}');
1336 environments_.push_back(name);
1338 if (name == "array" || name == "subarray") {
1339 docstring const valign = parse_verbatim_option() + 'c';
1340 docstring const halign = parse_verbatim_item();
1341 cell->push_back(MathAtom(new InsetMathArray(name,
1342 InsetMathGrid::guessColumns(halign), 1, (char)valign[0], halign)));
1343 parse2(cell->back(), FLAG_END, mode, false);
1346 else if (name == "tabular") {
1347 docstring const valign = parse_verbatim_option() + 'c';
1348 docstring const halign = parse_verbatim_item();
1349 cell->push_back(MathAtom(new InsetMathTabular(name,
1350 InsetMathGrid::guessColumns(halign), 1, (char)valign[0], halign)));
1351 parse2(cell->back(), FLAG_END, InsetMath::TEXT_MODE, false);
1354 else if (name == "split" || name == "cases") {
1355 cell->push_back(createInsetMath(name));
1356 parse2(cell->back(), FLAG_END, mode, false);
1359 else if (name == "alignedat") {
1360 docstring const valign = parse_verbatim_option() + 'c';
1361 // ignore this for a while
1363 cell->push_back(MathAtom(new InsetMathSplit(name, (char)valign[0])));
1364 parse2(cell->back(), FLAG_END, mode, false);
1367 else if (name == "math") {
1368 cell->push_back(MathAtom(new InsetMathHull(hullSimple)));
1369 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, true);
1372 else if (name == "equation" || name == "equation*"
1373 || name == "displaymath") {
1374 cell->push_back(MathAtom(new InsetMathHull(hullEquation)));
1375 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, (name == "equation"));
1378 else if (name == "eqnarray" || name == "eqnarray*") {
1379 cell->push_back(MathAtom(new InsetMathHull(hullEqnArray)));
1380 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, !stared(name));
1383 else if (name == "align" || name == "align*") {
1384 cell->push_back(MathAtom(new InsetMathHull(hullAlign)));
1385 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, !stared(name));
1388 else if (name == "flalign" || name == "flalign*") {
1389 cell->push_back(MathAtom(new InsetMathHull(hullFlAlign)));
1390 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, !stared(name));
1393 else if (name == "alignat" || name == "alignat*") {
1394 // ignore this for a while
1396 cell->push_back(MathAtom(new InsetMathHull(hullAlignAt)));
1397 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, !stared(name));
1400 else if (name == "xalignat" || name == "xalignat*") {
1401 // ignore this for a while
1403 cell->push_back(MathAtom(new InsetMathHull(hullXAlignAt)));
1404 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, !stared(name));
1407 else if (name == "xxalignat") {
1408 // ignore this for a while
1410 cell->push_back(MathAtom(new InsetMathHull(hullXXAlignAt)));
1411 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, !stared(name));
1414 else if (name == "multline" || name == "multline*") {
1415 cell->push_back(MathAtom(new InsetMathHull(hullMultline)));
1416 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, !stared(name));
1419 else if (name == "gather" || name == "gather*") {
1420 cell->push_back(MathAtom(new InsetMathHull(hullGather)));
1421 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, !stared(name));
1424 else if (latexkeys const * l = in_word_set(name)) {
1425 if (l->inset == "matrix") {
1426 cell->push_back(createInsetMath(name));
1427 parse2(cell->back(), FLAG_END, mode, false);
1428 } else if (l->inset == "split") {
1429 docstring const valign = parse_verbatim_option() + 'c';
1430 cell->push_back(MathAtom(new InsetMathSplit(name, (char)valign[0])));
1431 parse2(cell->back(), FLAG_END, mode, false);
1434 if (!(mode_ & Parse::QUIET)) {
1436 lyxerr << "found math environment `"
1438 << "' in symbols file with unsupported inset `"
1439 << to_utf8(l->inset)
1442 // create generic environment inset
1443 cell->push_back(MathAtom(new InsetMathEnv(name)));
1444 parse(cell->back().nucleus()->cell(0), FLAG_END, mode);
1450 if (!(mode_ & Parse::QUIET)) {
1452 lyxerr << "found unknown math environment '"
1453 << to_utf8(name) << "'" << endl;
1455 // create generic environment inset
1456 cell->push_back(MathAtom(new InsetMathEnv(name)));
1457 parse(cell->back().nucleus()->cell(0), FLAG_END, mode);
1461 else if (t.cs() == "kern") {
1465 Token const & t = getToken();
1471 if (isValidLength(to_utf8(s)))
1474 cell->push_back(MathAtom(new InsetMathKern(s)));
1477 else if (t.cs() == "label") {
1478 // FIXME: This is swallowed in inline formulas
1479 docstring label = parse_verbatim_item();
1482 if (grid.asHullInset()) {
1483 grid.asHullInset()->label(cellrow, label);
1485 cell->push_back(createInsetMath(t.cs()));
1486 cell->push_back(MathAtom(new InsetMathBrace(ar)));
1490 else if (t.cs() == "choose" || t.cs() == "over"
1491 || t.cs() == "atop" || t.cs() == "brace"
1492 || t.cs() == "brack") {
1493 MathAtom at = createInsetMath(t.cs());
1494 at.nucleus()->cell(0) = *cell;
1496 parse(at.nucleus()->cell(1), flags, mode);
1497 cell->push_back(at);
1501 else if (t.cs() == "color") {
1502 docstring const color = parse_verbatim_item();
1503 cell->push_back(MathAtom(new InsetMathColor(true, color)));
1504 parse(cell->back().nucleus()->cell(0), flags, mode);
1508 else if (t.cs() == "textcolor") {
1509 docstring const color = parse_verbatim_item();
1510 cell->push_back(MathAtom(new InsetMathColor(false, color)));
1511 parse(cell->back().nucleus()->cell(0), FLAG_ITEM, InsetMath::TEXT_MODE);
1514 else if (t.cs() == "normalcolor") {
1515 cell->push_back(createInsetMath(t.cs()));
1516 parse(cell->back().nucleus()->cell(0), flags, mode);
1520 else if (t.cs() == "substack") {
1521 cell->push_back(createInsetMath(t.cs()));
1522 parse2(cell->back(), FLAG_ITEM, mode, false);
1525 else if (t.cs() == "xymatrix") {
1526 odocstringstream os;
1527 while (good() && nextToken().cat() != catBegin)
1528 os << getToken().asInput();
1529 cell->push_back(createInsetMath(t.cs() + os.str()));
1530 parse2(cell->back(), FLAG_ITEM, mode, false);
1533 else if (t.cs() == "framebox" || t.cs() == "makebox") {
1534 cell->push_back(createInsetMath(t.cs()));
1535 parse(cell->back().nucleus()->cell(0), FLAG_OPTION, InsetMath::TEXT_MODE);
1536 parse(cell->back().nucleus()->cell(1), FLAG_OPTION, InsetMath::TEXT_MODE);
1537 parse(cell->back().nucleus()->cell(2), FLAG_ITEM, InsetMath::TEXT_MODE);
1540 else if (t.cs() == "tag") {
1541 if (nextToken().character() == '*') {
1543 cell->push_back(createInsetMath(t.cs() + '*'));
1545 cell->push_back(createInsetMath(t.cs()));
1546 parse(cell->back().nucleus()->cell(0), FLAG_ITEM, InsetMath::TEXT_MODE);
1550 else if (t.cs() == "infer") {
1552 parse(ar, FLAG_OPTION, mode);
1553 cell->push_back(createInsetMath(t.cs()));
1554 parse2(cell->back(), FLAG_ITEM, mode, false);
1558 else if (1 && t.cs() == "ar") {
1559 auto_ptr<InsetMathXYArrow> p(new InsetMathXYArrow);
1560 // try to read target
1561 parse(p->cell(0), FLAG_OTPTION, mode);
1562 // try to read label
1563 if (nextToken().cat() == catSuper || nextToken().cat() == catSub) {
1564 p->up_ = nextToken().cat() == catSuper;
1566 parse(p->cell(1), FLAG_ITEM, mode);
1567 //lyxerr << "read label: " << p->cell(1) << endl;
1570 cell->push_back(MathAtom(p.release()));
1571 //lyxerr << "read cell: " << cell << endl;
1575 else if (t.cs() == "lyxmathsym") {
1577 if (getToken().cat() != catBegin) {
1578 error("'{' expected in \\" + t.cs());
1583 CatCode cat = nextToken().cat();
1584 while (good() && (count || cat != catEnd)) {
1585 if (cat == catBegin)
1587 else if (cat == catEnd)
1589 cmd += getToken().asInput();
1590 cat = nextToken().cat();
1592 if (getToken().cat() != catEnd) {
1593 error("'}' expected in \\" + t.cs());
1597 cmd = Encodings::fromLaTeXCommand(cmd, rem);
1598 for (size_t i = 0; i < cmd.size(); ++i)
1599 cell->push_back(MathAtom(new InsetMathChar(cmd[i])));
1601 MathAtom at = createInsetMath(t.cs());
1602 cell->push_back(at);
1604 if (!mathed_parse_cell(ar, '{' + rem + '}', mode_))
1610 else if (t.cs().size()) {
1611 latexkeys const * l = in_word_set(t.cs());
1613 if (l->inset == "big") {
1615 docstring const delim = getToken().asInput();
1616 if (InsetMathBig::isBigInsetDelim(delim))
1617 cell->push_back(MathAtom(
1618 new InsetMathBig(t.cs(), delim)));
1620 cell->push_back(createInsetMath(t.cs()));
1625 else if (l->inset == "font") {
1626 cell->push_back(createInsetMath(t.cs()));
1627 parse(cell->back().nucleus()->cell(0),
1628 FLAG_ITEM, asMode(mode, l->extra));
1631 else if (l->inset == "oldfont") {
1632 cell->push_back(createInsetMath(t.cs()));
1633 parse(cell->back().nucleus()->cell(0),
1634 flags | FLAG_ALIGN, asMode(mode, l->extra));
1635 if (prevToken().cat() != catAlign &&
1636 prevToken().cs() != "\\")
1641 else if (l->inset == "style") {
1642 cell->push_back(createInsetMath(t.cs()));
1643 parse(cell->back().nucleus()->cell(0),
1644 flags | FLAG_ALIGN, mode);
1645 if (prevToken().cat() != catAlign &&
1646 prevToken().cs() != "\\")
1652 MathAtom at = createInsetMath(t.cs());
1653 for (InsetMath::idx_type i = 0; i < at->nargs(); ++i)
1654 parse(at.nucleus()->cell(i),
1655 FLAG_ITEM, asMode(mode, l->extra));
1656 cell->push_back(at);
1661 bool is_unicode_symbol = false;
1662 if (mode == InsetMath::TEXT_MODE) {
1664 docstring cmd = prevToken().asInput();
1666 CatCode cat = nextToken().cat();
1667 if (cat == catBegin) {
1669 while (good() && (count || cat != catEnd)) {
1670 cat = nextToken().cat();
1671 cmd += getToken().asInput();
1673 if (cat == catBegin)
1675 else if (cat == catEnd)
1681 Encodings::fromLaTeXCommand(cmd, is_combining);
1683 if (cat == catLetter)
1685 cmd += getToken().asInput();
1687 if (cat == catLetter)
1689 c = Encodings::fromLaTeXCommand(cmd, is_combining);
1692 is_unicode_symbol = true;
1693 cell->push_back(MathAtom(new InsetMathChar(c)));
1695 while (num_tokens--)
1699 if (!is_unicode_symbol) {
1700 MathAtom at = createInsetMath(t.cs());
1701 InsetMath::mode_type m = mode;
1702 //if (m == InsetMath::UNDECIDED_MODE)
1703 //lyxerr << "default creation: m1: " << m << endl;
1704 if (at->currentMode() != InsetMath::UNDECIDED_MODE)
1705 m = at->currentMode();
1706 //lyxerr << "default creation: m2: " << m << endl;
1707 InsetMath::idx_type start = 0;
1708 // this fails on \bigg[...\bigg]
1710 //parse(opt, FLAG_OPTION, InsetMath::VERBATIM_MODE);
1713 // at.nucleus()->cell(0) = opt;
1715 for (InsetMath::idx_type i = start; i < at->nargs(); ++i) {
1716 parse(at.nucleus()->cell(i), FLAG_ITEM, m);
1719 cell->push_back(at);
1725 if (flags & FLAG_LEAVE) {
1726 flags &= ~FLAG_LEAVE;
1735 } // anonymous namespace
1738 bool mathed_parse_cell(MathData & ar, docstring const & str, Parse::flags f)
1740 return Parser(str, f).parse(ar, 0, f & Parse::TEXTMODE ?
1741 InsetMath::TEXT_MODE : InsetMath::MATH_MODE);
1745 bool mathed_parse_cell(MathData & ar, istream & is, Parse::flags f)
1747 return Parser(is, f).parse(ar, 0, f & Parse::TEXTMODE ?
1748 InsetMath::TEXT_MODE : InsetMath::MATH_MODE);
1752 bool mathed_parse_normal(MathAtom & t, docstring const & str, Parse::flags f)
1754 return Parser(str, f).parse(t);
1758 bool mathed_parse_normal(MathAtom & t, Lexer & lex, Parse::flags f)
1760 return Parser(lex, f).parse(t);
1764 bool mathed_parse_normal(InsetMathGrid & grid, docstring const & str, Parse::flags f)
1766 return Parser(str, f).parse1(grid, 0, f & Parse::TEXTMODE ?
1767 InsetMath::TEXT_MODE : InsetMath::MATH_MODE, false);
1773 fill(theCatcode, theCatcode + 128, catOther);
1774 fill(theCatcode + 'a', theCatcode + 'z' + 1, catLetter);
1775 fill(theCatcode + 'A', theCatcode + 'Z' + 1, catLetter);
1777 theCatcode[int('\\')] = catEscape;
1778 theCatcode[int('{')] = catBegin;
1779 theCatcode[int('}')] = catEnd;
1780 theCatcode[int('$')] = catMath;
1781 theCatcode[int('&')] = catAlign;
1782 theCatcode[int('\n')] = catNewline;
1783 theCatcode[int('#')] = catParameter;
1784 theCatcode[int('^')] = catSuper;
1785 theCatcode[int('_')] = catSub;
1786 theCatcode[int(0x7f)] = catIgnore;
1787 theCatcode[int(' ')] = catSpace;
1788 theCatcode[int('\t')] = catSpace;
1789 theCatcode[int('\r')] = catNewline;
1790 theCatcode[int('~')] = catActive;
1791 theCatcode[int('%')] = catComment;