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)
105 return subst(subst(subst(subst(subst(subst(subst(subst(subst(str,
106 from_ascii("\\"), from_ascii("\\backslash ")),
107 from_ascii("^"), from_ascii("\\mathcircumflex ")),
108 from_ascii("_"), from_ascii("\\_")),
109 from_ascii("$"), from_ascii("\\$")),
110 from_ascii("#"), from_ascii("\\#")),
111 from_ascii("&"), from_ascii("\\&")),
112 from_ascii("%"), from_ascii("\\%")),
113 from_ascii("{"), from_ascii("\\{")),
114 from_ascii("}"), from_ascii("\\}"));
119 * Add the row \p cellrow to \p grid.
120 * \returns wether the row could be added. Adding a row can fail for
121 * environments like "equation" that have a fixed number of rows.
123 bool addRow(InsetMathGrid & grid, InsetMathGrid::row_type & cellrow,
124 docstring const & vskip, bool allow_newpage_ = true)
127 if (cellrow == grid.nrows()) {
128 //lyxerr << "adding row " << cellrow << endl;
129 grid.addRow(cellrow - 1);
130 if (cellrow == grid.nrows()) {
131 // We can't add a row to this grid, so let's
132 // append the content of this cell to the previous
134 // This does not happen in well formed .lyx files,
135 // but LyX versions 1.3.x and older could create
136 // such files and tex2lyx can still do that.
138 lyxerr << "ignoring extra row";
140 lyxerr << " with extra space " << to_utf8(vskip);
142 lyxerr << " with no page break allowed";
143 lyxerr << '.' << endl;
147 grid.vcrskip(Length(to_utf8(vskip)), cellrow - 1);
148 grid.rowinfo(cellrow - 1).allow_newpage_ = allow_newpage_;
154 * Add the column \p cellcol to \p grid.
155 * \returns wether the column could be added. Adding a column can fail for
156 * environments like "eqnarray" that have a fixed number of columns.
158 bool addCol(InsetMathGrid & grid, InsetMathGrid::col_type & cellcol)
161 if (cellcol == grid.ncols()) {
162 //lyxerr << "adding column " << cellcol << endl;
163 grid.addCol(cellcol);
164 if (cellcol == grid.ncols()) {
165 // We can't add a column to this grid, so let's
166 // append the content of this cell to the previous
168 // This does not happen in well formed .lyx files,
169 // but LyX versions 1.3.x and older could create
170 // such files and tex2lyx can still do that.
172 lyxerr << "ignoring extra column." << endl;
181 * Check wether the last row is empty and remove it if yes.
182 * Otherwise the following code
190 * will result in a grid with 3 rows (+ the dummy row that is always present),
191 * because the last '\\' opens a new row.
193 void delEmptyLastRow(InsetMathGrid & grid)
195 InsetMathGrid::row_type const row = grid.nrows() - 1;
196 for (InsetMathGrid::col_type col = 0; col < grid.ncols(); ++col) {
197 if (!grid.cell(grid.index(row, col)).empty())
200 // Copy the row information of the empty row (which would contain the
201 // last hline in the example above) to the dummy row and delete the
203 grid.rowinfo(row + 1) = grid.rowinfo(row);
208 // These are TeX's catcodes
210 catEscape, // 0 backslash
220 catSpace, // 10 space
221 catLetter, // 11 a-zA-Z
222 catOther, // 12 none of the above
225 catInvalid // 15 <delete>
228 CatCode theCatcode[128];
231 inline CatCode catcode(char_type c)
233 /* The only characters that are not catOther lie in the pure ASCII
234 * range. Therefore theCatcode has only 128 entries.
235 * TeX itself deals with 8bit characters, so if needed this table
236 * could be enlarged to 256 entries.
237 * Any larger value does not make sense, since the fact that we use
238 * unicode internally does not change Knuth's TeX engine.
239 * Apart from that a table for the full 21bit UCS4 range would waste
240 * too much memory. */
244 return theCatcode[c];
249 FLAG_ALIGN = 1 << 0, // next & or \\ ends the parsing process
250 FLAG_BRACE_LAST = 1 << 1, // next closing brace ends the parsing
251 FLAG_RIGHT = 1 << 2, // next \\right ends the parsing process
252 FLAG_END = 1 << 3, // next \\end ends the parsing process
253 FLAG_BRACK_LAST = 1 << 4, // next closing bracket ends the parsing
254 FLAG_TEXTMODE = 1 << 5, // we are in a box
255 FLAG_ITEM = 1 << 6, // read a (possibly braced) token
256 FLAG_LEAVE = 1 << 7, // leave the loop at the end
257 FLAG_SIMPLE = 1 << 8, // next $ leaves the loop
258 FLAG_EQUATION = 1 << 9, // next \] leaves the loop
259 FLAG_SIMPLE2 = 1 << 10, // next \) leaves the loop
260 FLAG_OPTION = 1 << 11, // read [...] style option
261 FLAG_BRACED = 1 << 12 // read {...} style argument
266 // Helper class for parsing
272 Token() : cs_(), char_(0), cat_(catIgnore) {}
274 Token(char_type c, CatCode cat) : cs_(), char_(c), cat_(cat) {}
276 explicit Token(docstring const & cs) : cs_(cs), char_(0), cat_(catIgnore) {}
279 docstring const & cs() const { return cs_; }
281 CatCode cat() const { return cat_; }
283 char_type character() const { return char_; }
285 docstring asString() const { return cs_.size() ? cs_ : docstring(1, char_); }
287 docstring asInput() const { return cs_.size() ? '\\' + cs_ : docstring(1, char_); }
299 ostream & operator<<(ostream & os, Token const & t)
302 docstring const & cs = t.cs();
303 // FIXME: For some strange reason, the stream operator instanciate
304 // a new Token before outputting the contents of t.cs().
305 // Because of this the line
307 // below becomes recursive.
308 // In order to avoid that we return early:
311 os << '\\' << to_utf8(cs);
313 else if (t.cat() == catLetter)
316 os << '[' << t.character() << ',' << t.cat() << ']';
324 typedef InsetMath::mode_type mode_type;
326 typedef Parse::flags parse_mode;
329 Parser(Lexer & lex, parse_mode mode);
330 /// Only use this for reading from .lyx file format, for the reason
331 /// see Parser::tokenize(istream &).
332 Parser(istream & is, parse_mode mode);
334 Parser(docstring const & str, parse_mode mode);
337 bool parse(MathAtom & at);
339 bool parse(MathData & array, unsigned flags, mode_type mode);
341 bool parse1(InsetMathGrid & grid, unsigned flags, mode_type mode,
344 MathData parse(unsigned flags, mode_type mode);
346 int lineno() const { return lineno_; }
352 void parse2(MathAtom & at, unsigned flags, mode_type mode, bool numbered);
353 /// get arg delimited by 'left' and 'right'
354 docstring getArg(char_type left, char_type right);
358 void error(string const & msg);
359 void error(docstring const & msg) { error(to_utf8(msg)); }
360 /// dump contents to screen
362 /// Only use this for reading from .lyx file format (see
363 /// implementation for reason)
364 void tokenize(istream & is);
366 void tokenize(docstring const & s);
368 void skipSpaceTokens(idocstream & is, char_type c);
370 void push_back(Token const & t);
374 Token const & prevToken() const;
376 Token const & nextToken() const;
378 Token const & getToken();
379 /// skips spaces if any
382 void lex(docstring const & s);
386 docstring parse_verbatim_item();
388 docstring parse_verbatim_option();
393 vector<Token> tokens_;
396 /// Stack of active environments
397 vector<docstring> environments_;
405 Parser::Parser(Lexer & lexer, parse_mode mode)
406 : lineno_(lexer.lineNumber()), pos_(0), mode_(mode), success_(true)
408 tokenize(lexer.getStream());
413 Parser::Parser(istream & is, parse_mode mode)
414 : lineno_(0), pos_(0), mode_(mode), success_(true)
420 Parser::Parser(docstring const & str, parse_mode mode)
421 : lineno_(0), pos_(0), mode_(mode), success_(true)
427 void Parser::push_back(Token const & t)
429 tokens_.push_back(t);
433 void Parser::pop_back()
439 Token const & Parser::prevToken() const
441 static const Token dummy;
442 return pos_ > 0 ? tokens_[pos_ - 1] : dummy;
446 Token const & Parser::nextToken() const
448 static const Token dummy;
449 return good() ? tokens_[pos_] : dummy;
453 Token const & Parser::getToken()
455 static const Token dummy;
456 //lyxerr << "looking at token " << tokens_[pos_] << " pos: " << pos_ << endl;
457 return good() ? tokens_[pos_++] : dummy;
461 void Parser::skipSpaces()
463 while (nextToken().cat() == catSpace || nextToken().cat() == catNewline)
468 void Parser::putback()
474 bool Parser::good() const
476 return pos_ < tokens_.size();
480 char_type Parser::getChar()
483 error("The input stream is not well...");
487 return tokens_[pos_++].character();
491 docstring Parser::getArg(char_type left, char_type right)
496 char_type c = getChar();
501 while ((c = getChar()) != right && good())
508 void Parser::skipSpaceTokens(idocstream & is, char_type c)
510 // skip trailing spaces
511 while (catcode(c) == catSpace || catcode(c) == catNewline)
514 //lyxerr << "putting back: " << c << endl;
519 void Parser::tokenize(istream & is)
521 // eat everything up to the next \end_inset or end of stream
522 // and store it in s for further tokenization
527 if (s.size() >= 10 && s.substr(s.size() - 10) == "\\end_inset") {
528 s = s.substr(0, s.size() - 10);
532 // Remove the space after \end_inset
533 if (is.get(c) && c != ' ')
537 tokenize(from_utf8(s));
541 void Parser::tokenize(docstring const & buffer)
543 idocstringstream is(mode_ & Parse::VERBATIM ?
544 escapeSpecialChars(buffer) : buffer, ios::in | ios::binary);
548 //lyxerr << "reading c: " << c << endl;
550 switch (catcode(c)) {
554 if (catcode(c) == catNewline)
555 ; //push_back(Token("par"));
557 push_back(Token('\n', catNewline));
565 while (is.get(c) && catcode(c) != catNewline)
575 error("unexpected end of input");
578 if (catcode(c) == catLetter) {
580 while (is.get(c) && catcode(c) == catLetter)
582 skipSpaceTokens(is, c);
591 push_back(Token(c, catcode(c)));
593 skipSpaceTokens(is, c);
598 if (!(mode_ & Parse::QUIET))
599 lyxerr << "ignoring a char: " << int(c) << endl;
604 push_back(Token(c, catcode(c)));
614 void Parser::dump() const
616 lyxerr << "\nTokens: ";
617 for (unsigned i = 0; i < tokens_.size(); ++i) {
620 lyxerr << tokens_[i];
622 lyxerr << " pos: " << pos_ << endl;
626 void Parser::error(string const & msg)
629 if (!(mode_ & Parse::QUIET)) {
630 lyxerr << "Line ~" << lineno_ << ": Math parse error: "
637 bool Parser::parse(MathAtom & at)
641 parse(ar, false, InsetMath::UNDECIDED_MODE);
642 if (ar.size() != 1 || ar.front()->getType() == hullNone) {
643 if (!(mode_ & Parse::QUIET))
644 lyxerr << "unusual contents found: " << ar << endl;
645 at = MathAtom(new InsetMathPar(ar));
646 //if (at->nargs() > 0)
647 // at.nucleus()->cell(0) = ar;
649 // lyxerr << "unusual contents found: " << ar << endl;
657 docstring Parser::parse_verbatim_option()
661 if (nextToken().character() == '[') {
662 Token t = getToken();
663 for (Token t = getToken(); t.character() != ']' && good(); t = getToken()) {
664 if (t.cat() == catBegin) {
666 res += '{' + parse_verbatim_item() + '}';
675 docstring Parser::parse_verbatim_item()
679 if (nextToken().cat() == catBegin) {
680 Token t = getToken();
681 for (Token t = getToken(); t.cat() != catEnd && good(); t = getToken()) {
682 if (t.cat() == catBegin) {
684 res += '{' + parse_verbatim_item() + '}';
694 MathData Parser::parse(unsigned flags, mode_type mode)
697 parse(ar, flags, mode);
702 bool Parser::parse(MathData & array, unsigned flags, mode_type mode)
704 InsetMathGrid grid(1, 1);
705 parse1(grid, flags, mode, false);
706 array = grid.cell(0);
711 void Parser::parse2(MathAtom & at, const unsigned flags, const mode_type mode,
714 parse1(*(at.nucleus()->asGridInset()), flags, mode, numbered);
718 bool Parser::parse1(InsetMathGrid & grid, unsigned flags,
719 const mode_type mode, const bool numbered)
722 InsetMathGrid::row_type cellrow = 0;
723 InsetMathGrid::col_type cellcol = 0;
724 MathData * cell = &grid.cell(grid.index(cellrow, cellcol));
726 if (grid.asHullInset())
727 grid.asHullInset()->numbered(cellrow, numbered);
730 //lyxerr << " flags: " << flags << endl;
731 //lyxerr << " mode: " << mode << endl;
732 //lyxerr << "grid: " << grid << endl;
735 Token const & t = getToken();
738 lyxerr << "t: " << t << " flags: " << flags << endl;
739 lyxerr << "mode: " << mode << endl;
744 if (flags & FLAG_ITEM) {
746 if (t.cat() == catBegin) {
747 // skip the brace and collect everything to the next matching
749 parse1(grid, FLAG_BRACE_LAST, mode, numbered);
753 // handle only this single token, leave the loop if done
758 if (flags & FLAG_BRACED) {
759 if (t.cat() == catSpace)
762 if (t.cat() != catBegin) {
763 error("opening brace expected");
767 // skip the brace and collect everything to the next matching
769 flags = FLAG_BRACE_LAST;
773 if (flags & FLAG_OPTION) {
774 if (t.cat() == catOther && t.character() == '[') {
776 parse(ar, FLAG_BRACK_LAST, mode);
779 // no option found, put back token and we are done
788 if (t.cat() == catMath) {
789 if (mode != InsetMath::MATH_MODE) {
790 // we are inside some text mode thingy, so opening new math is allowed
791 Token const & n = getToken();
792 if (n.cat() == catMath) {
793 // TeX's $$...$$ syntax for displayed math
794 cell->push_back(MathAtom(new InsetMathHull(hullEquation)));
795 parse2(cell->back(), FLAG_SIMPLE, InsetMath::MATH_MODE, false);
796 getToken(); // skip the second '$' token
798 // simple $...$ stuff
800 cell->push_back(MathAtom(new InsetMathHull(hullSimple)));
801 parse2(cell->back(), FLAG_SIMPLE, InsetMath::MATH_MODE, false);
805 else if (flags & FLAG_SIMPLE) {
806 // this is the end of the formula
811 error("something strange in the parser");
816 else if (t.cat() == catLetter)
817 cell->push_back(MathAtom(new InsetMathChar(t.character())));
819 else if (t.cat() == catSpace && mode != InsetMath::MATH_MODE) {
820 if (cell->empty() || cell->back()->getChar() != ' ')
821 cell->push_back(MathAtom(new InsetMathChar(t.character())));
824 else if (t.cat() == catNewline && mode != InsetMath::MATH_MODE) {
825 if (cell->empty() || cell->back()->getChar() != ' ')
826 cell->push_back(MathAtom(new InsetMathChar(' ')));
829 else if (t.cat() == catParameter) {
830 Token const & n = getToken();
831 cell->push_back(MathAtom(new MathMacroArgument(n.character()-'0')));
834 else if (t.cat() == catActive)
835 cell->push_back(MathAtom(new InsetMathChar(t.character())));
837 else if (t.cat() == catBegin) {
839 parse(ar, FLAG_BRACE_LAST, mode);
840 // do not create a BraceInset if they were written by LyX
841 // this helps to keep the annoyance of "a choose b" to a minimum
842 if (ar.size() == 1 && ar[0]->extraBraces())
845 cell->push_back(MathAtom(new InsetMathBrace(ar)));
848 else if (t.cat() == catEnd) {
849 if (flags & FLAG_BRACE_LAST)
851 error("found '}' unexpectedly");
852 //LASSERT(false, /**/);
853 //add(cell, '}', LM_TC_TEX);
856 else if (t.cat() == catAlign) {
857 //lyxerr << " column now " << (cellcol + 1)
858 // << " max: " << grid.ncols() << endl;
859 if (flags & FLAG_ALIGN)
861 if (addCol(grid, cellcol))
862 cell = &grid.cell(grid.index(cellrow, cellcol));
865 else if (t.cat() == catSuper || t.cat() == catSub) {
866 bool up = (t.cat() == catSuper);
867 // we need no new script inset if the last thing was a scriptinset,
868 // which has that script already not the same script already
870 cell->push_back(MathAtom(new InsetMathScript(up)));
871 else if (cell->back()->asScriptInset() &&
872 !cell->back()->asScriptInset()->has(up))
873 cell->back().nucleus()->asScriptInset()->ensure(up);
874 else if (cell->back()->asScriptInset())
875 cell->push_back(MathAtom(new InsetMathScript(up)));
877 cell->back() = MathAtom(new InsetMathScript(cell->back(), up));
878 InsetMathScript * p = cell->back().nucleus()->asScriptInset();
879 // special handling of {}-bases
880 // Here we could remove the brace inset for things
881 // like {a'}^2 and add the braces back in
882 // InsetMathScript::write().
883 // We do not do it, since it is not possible to detect
884 // reliably whether the braces are needed because the
885 // nucleus contains more than one symbol, or whether
886 // they are needed for unknown commands like \xx{a}_0
887 // or \yy{a}{b}_0. This was done in revision 14819
888 // in an unreliable way. See this thread
889 // http://www.mail-archive.com/lyx-devel%40lists.lyx.org/msg104917.html
891 parse(p->cell(p->idxOfScript(up)), FLAG_ITEM, mode);
898 else if (t.character() == ']' && (flags & FLAG_BRACK_LAST)) {
899 //lyxerr << "finished reading option" << endl;
903 else if (t.cat() == catOther)
904 cell->push_back(MathAtom(new InsetMathChar(t.character())));
906 else if (t.cat() == catComment) {
909 Token const & t = getToken();
910 if (t.cat() == catNewline)
914 cell->push_back(MathAtom(new InsetMathComment(s)));
922 else if (t.cs() == "lyxlock") {
924 cell->back().nucleus()->lock(true);
927 else if ((t.cs() == "global" && nextToken().cs() == "def") ||
929 if (t.cs() == "global")
933 docstring name = getToken().cs();
938 while (good() && nextToken().cat() != catBegin) {
939 pars += getToken().cs();
946 parse(def, FLAG_ITEM, InsetMath::UNDECIDED_MODE);
948 // is a version for display attached?
951 if (nextToken().cat() == catBegin)
952 parse(display, FLAG_ITEM, InsetMath::MATH_MODE);
954 cell->push_back(MathAtom(new MathMacroTemplate(name, nargs,
955 0, MacroTypeDef, vector<MathData>(), def, display)));
958 else if (t.cs() == "newcommand" ||
959 t.cs() == "renewcommand" ||
960 t.cs() == "newlyxcommand") {
962 if (getToken().cat() != catBegin) {
963 error("'{' in \\newcommand expected (1) ");
966 docstring name = getToken().cs();
967 if (getToken().cat() != catEnd) {
968 error("'}' in \\newcommand expected");
973 docstring const arg = getArg('[', ']');
976 nargs = convert<int>(arg);
978 // optional argument given?
981 vector<MathData> optionalValues;
982 while (nextToken().character() == '[') {
984 optionalValues.push_back(MathData());
985 parse(optionalValues[optionals], FLAG_BRACK_LAST, mode);
990 parse(def, FLAG_ITEM, InsetMath::UNDECIDED_MODE);
992 // is a version for display attached?
995 if (nextToken().cat() == catBegin)
996 parse(display, FLAG_ITEM, InsetMath::MATH_MODE);
998 cell->push_back(MathAtom(new MathMacroTemplate(name, nargs,
999 optionals, MacroTypeNewcommand, optionalValues, def, display)));
1003 else if (t.cs() == "newcommandx" ||
1004 t.cs() == "renewcommandx") {
1005 // \newcommandx{\foo}[2][usedefault, addprefix=\global,1=default]{#1,#2}
1008 if (nextToken().cat() == catBegin) {
1010 name = getToken().cs();
1011 if (getToken().cat() != catEnd) {
1012 error("'}' in \\newcommandx expected");
1016 name = getToken().cs();
1019 docstring const arg = getArg('[', ']');
1021 error("[num] in \\newcommandx expected");
1024 int nargs = convert<int>(arg);
1028 vector<MathData> optionalValues;
1029 if (nextToken().character() == '[') {
1033 // handle 'opt=value' options, separated by ','.
1035 while (nextToken().character() != ']' && good()) {
1036 if (nextToken().character() >= '1'
1037 && nextToken().character() <= '9') {
1038 // optional value -> get parameter number
1039 int n = getChar() - '0';
1041 error("Arity of \\newcommandx too low "
1042 "for given optional parameter.");
1047 if (getToken().character() != '=') {
1048 error("'=' and optional parameter value "
1049 "expected for \\newcommandx");
1054 int optNum = max(size_t(n), optionalValues.size());
1055 optionalValues.resize(optNum);
1056 optionalValues[n - 1].clear();
1057 while (nextToken().character() != ']'
1058 && nextToken().character() != ',') {
1060 parse(data, FLAG_ITEM, InsetMath::UNDECIDED_MODE);
1061 optionalValues[n - 1].append(data);
1063 optionals = max(n, optionals);
1064 } else if (nextToken().cat() == catLetter) {
1065 // we in fact ignore every non-optional
1070 while (nextToken().cat() == catLetter)
1076 if (nextToken().character() == '=') {
1078 while (nextToken().character() != ']'
1079 && nextToken().character() != ',')
1080 parse(value, FLAG_ITEM,
1081 InsetMath::UNDECIDED_MODE);
1084 error("option for \\newcommandx expected");
1090 if (nextToken().character() == ',') {
1093 } else if (nextToken().character() != ']') {
1094 error("Expecting ',' or ']' in options "
1095 "of \\newcommandx");
1108 parse(def, FLAG_ITEM, InsetMath::UNDECIDED_MODE);
1110 // is a version for display attached?
1113 if (nextToken().cat() == catBegin)
1114 parse(display, FLAG_ITEM, InsetMath::MATH_MODE);
1116 cell->push_back(MathAtom(new MathMacroTemplate(name, nargs,
1117 optionals, MacroTypeNewcommandx, optionalValues, def,
1121 else if (t.cs() == "(") {
1122 cell->push_back(MathAtom(new InsetMathHull(hullSimple)));
1123 parse2(cell->back(), FLAG_SIMPLE2, InsetMath::MATH_MODE, false);
1126 else if (t.cs() == "[") {
1127 cell->push_back(MathAtom(new InsetMathHull(hullEquation)));
1128 parse2(cell->back(), FLAG_EQUATION, InsetMath::MATH_MODE, false);
1131 else if (t.cs() == "protect")
1132 // ignore \\protect, will hopefully be re-added during output
1135 else if (t.cs() == "end") {
1136 if (flags & FLAG_END) {
1137 // eat environment name
1138 docstring const name = getArg('{', '}');
1139 if (environments_.empty())
1140 error("'found \\end{" + name +
1141 "}' without matching '\\begin{" +
1143 else if (name != environments_.back())
1144 error("'\\end{" + name +
1145 "}' does not match '\\begin{" +
1146 environments_.back() + "}'");
1148 environments_.pop_back();
1149 // Delete empty last row in matrix
1151 // If you abuse InsetMathGrid for
1152 // non-matrix like structures you
1153 // probably need to refine this test.
1154 // Right now we only have to test for
1155 // single line hull insets.
1156 if (grid.nrows() > 1)
1157 delEmptyLastRow(grid);
1161 error("found 'end' unexpectedly");
1164 else if (t.cs() == ")") {
1165 if (flags & FLAG_SIMPLE2)
1167 error("found '\\)' unexpectedly");
1170 else if (t.cs() == "]") {
1171 if (flags & FLAG_EQUATION)
1173 error("found '\\]' unexpectedly");
1176 else if (t.cs() == "\\") {
1177 if (flags & FLAG_ALIGN)
1180 if (nextToken().asInput() == "*") {
1182 added = addRow(grid, cellrow, docstring(), false);
1184 added = addRow(grid, cellrow, getArg('[', ']'));
1186 error("missing token after \\\\");
1189 if (grid.asHullInset())
1190 grid.asHullInset()->numbered(
1192 cell = &grid.cell(grid.index(cellrow,
1198 else if (t.cs() == "multicolumn") {
1199 // extract column count and insert dummy cells
1201 parse(count, FLAG_ITEM, mode);
1203 if (!extractNumber(count, cols)) {
1205 lyxerr << " can't extract number of cells from " << count << endl;
1207 // resize the table if necessary
1208 for (int i = 0; i < cols; ++i) {
1209 if (addCol(grid, cellcol)) {
1210 cell = &grid.cell(grid.index(
1212 // mark this as dummy
1213 grid.cellinfo(grid.index(
1214 cellrow, cellcol)).dummy_ = true;
1217 // the last cell is the real thing, not a dummy
1218 grid.cellinfo(grid.index(cellrow, cellcol)).dummy_ = false;
1220 // read special alignment
1222 parse(align, FLAG_ITEM, mode);
1223 //grid.cellinfo(grid.index(cellrow, cellcol)).align_ = extractString(align);
1225 // parse the remaining contents into the "real" cell
1226 parse(*cell, FLAG_ITEM, mode);
1230 else if (t.cs() == "limits")
1233 else if (t.cs() == "nolimits")
1236 else if (t.cs() == "nonumber") {
1237 if (grid.asHullInset())
1238 grid.asHullInset()->numbered(cellrow, false);
1241 else if (t.cs() == "number") {
1242 if (grid.asHullInset())
1243 grid.asHullInset()->numbered(cellrow, true);
1246 else if (t.cs() == "hline") {
1247 grid.rowinfo(cellrow).lines_ ++;
1250 else if (t.cs() == "sqrt") {
1252 parse(ar, FLAG_OPTION, mode);
1254 cell->push_back(MathAtom(new InsetMathRoot));
1255 cell->back().nucleus()->cell(0) = ar;
1256 parse(cell->back().nucleus()->cell(1), FLAG_ITEM, mode);
1258 cell->push_back(MathAtom(new InsetMathSqrt));
1259 parse(cell->back().nucleus()->cell(0), FLAG_ITEM, mode);
1263 else if (t.cs() == "unit") {
1264 // Allowed formats \unit[val]{unit}
1266 parse(ar, FLAG_OPTION, mode);
1268 cell->push_back(MathAtom(new InsetMathFrac(InsetMathFrac::UNIT)));
1269 cell->back().nucleus()->cell(0) = ar;
1270 parse(cell->back().nucleus()->cell(1), FLAG_ITEM, mode);
1272 cell->push_back(MathAtom(new InsetMathFrac(InsetMathFrac::UNIT, 1)));
1273 parse(cell->back().nucleus()->cell(0), FLAG_ITEM, mode);
1276 else if (t.cs() == "unitfrac") {
1277 // Here allowed formats are \unitfrac[val]{num}{denom}
1279 parse(ar, FLAG_OPTION, mode);
1281 cell->push_back(MathAtom(new InsetMathFrac(InsetMathFrac::UNITFRAC, 3)));
1282 cell->back().nucleus()->cell(2) = ar;
1284 cell->push_back(MathAtom(new InsetMathFrac(InsetMathFrac::UNITFRAC)));
1286 parse(cell->back().nucleus()->cell(0), FLAG_ITEM, mode);
1287 parse(cell->back().nucleus()->cell(1), FLAG_ITEM, mode);
1290 else if (t.cs() == "xrightarrow" || t.cs() == "xleftarrow") {
1291 cell->push_back(createInsetMath(t.cs()));
1292 parse(cell->back().nucleus()->cell(1), FLAG_OPTION, mode);
1293 parse(cell->back().nucleus()->cell(0), FLAG_ITEM, mode);
1296 else if (t.cs() == "ref" || t.cs() == "eqref" || t.cs() == "prettyref"
1297 || t.cs() == "pageref" || t.cs() == "vpageref" || t.cs() == "vref") {
1298 cell->push_back(MathAtom(new InsetMathRef(t.cs())));
1299 parse(cell->back().nucleus()->cell(1), FLAG_OPTION, mode);
1300 parse(cell->back().nucleus()->cell(0), FLAG_ITEM, mode);
1303 else if (t.cs() == "left") {
1305 Token const & tl = getToken();
1306 // \| and \Vert are equivalent, and InsetMathDelim
1308 // FIXME: fix this in InsetMathDelim itself!
1309 docstring const l = tl.cs() == "|" ? from_ascii("Vert") : tl.asString();
1311 parse(ar, FLAG_RIGHT, mode);
1315 Token const & tr = getToken();
1316 docstring const r = tr.cs() == "|" ? from_ascii("Vert") : tr.asString();
1317 cell->push_back(MathAtom(new InsetMathDelim(l, r, ar)));
1320 else if (t.cs() == "right") {
1321 if (flags & FLAG_RIGHT)
1323 //lyxerr << "got so far: '" << cell << "'" << endl;
1324 error("Unmatched right delimiter");
1328 else if (t.cs() == "begin") {
1329 docstring const name = getArg('{', '}');
1330 environments_.push_back(name);
1332 if (name == "array" || name == "subarray") {
1333 docstring const valign = parse_verbatim_option() + 'c';
1334 docstring const halign = parse_verbatim_item();
1335 cell->push_back(MathAtom(new InsetMathArray(name,
1336 InsetMathGrid::guessColumns(halign), 1, (char)valign[0], halign)));
1337 parse2(cell->back(), FLAG_END, mode, false);
1340 else if (name == "tabular") {
1341 docstring const valign = parse_verbatim_option() + 'c';
1342 docstring const halign = parse_verbatim_item();
1343 cell->push_back(MathAtom(new InsetMathTabular(name,
1344 InsetMathGrid::guessColumns(halign), 1, (char)valign[0], halign)));
1345 parse2(cell->back(), FLAG_END, InsetMath::TEXT_MODE, false);
1348 else if (name == "split" || name == "cases") {
1349 cell->push_back(createInsetMath(name));
1350 parse2(cell->back(), FLAG_END, mode, false);
1353 else if (name == "alignedat") {
1354 docstring const valign = parse_verbatim_option() + 'c';
1355 // ignore this for a while
1357 cell->push_back(MathAtom(new InsetMathSplit(name, (char)valign[0])));
1358 parse2(cell->back(), FLAG_END, mode, false);
1361 else if (name == "math") {
1362 cell->push_back(MathAtom(new InsetMathHull(hullSimple)));
1363 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, true);
1366 else if (name == "equation" || name == "equation*"
1367 || name == "displaymath") {
1368 cell->push_back(MathAtom(new InsetMathHull(hullEquation)));
1369 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, (name == "equation"));
1372 else if (name == "eqnarray" || name == "eqnarray*") {
1373 cell->push_back(MathAtom(new InsetMathHull(hullEqnArray)));
1374 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, !stared(name));
1377 else if (name == "align" || name == "align*") {
1378 cell->push_back(MathAtom(new InsetMathHull(hullAlign)));
1379 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, !stared(name));
1382 else if (name == "flalign" || name == "flalign*") {
1383 cell->push_back(MathAtom(new InsetMathHull(hullFlAlign)));
1384 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, !stared(name));
1387 else if (name == "alignat" || name == "alignat*") {
1388 // ignore this for a while
1390 cell->push_back(MathAtom(new InsetMathHull(hullAlignAt)));
1391 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, !stared(name));
1394 else if (name == "xalignat" || name == "xalignat*") {
1395 // ignore this for a while
1397 cell->push_back(MathAtom(new InsetMathHull(hullXAlignAt)));
1398 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, !stared(name));
1401 else if (name == "xxalignat") {
1402 // ignore this for a while
1404 cell->push_back(MathAtom(new InsetMathHull(hullXXAlignAt)));
1405 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, !stared(name));
1408 else if (name == "multline" || name == "multline*") {
1409 cell->push_back(MathAtom(new InsetMathHull(hullMultline)));
1410 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, !stared(name));
1413 else if (name == "gather" || name == "gather*") {
1414 cell->push_back(MathAtom(new InsetMathHull(hullGather)));
1415 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, !stared(name));
1418 else if (latexkeys const * l = in_word_set(name)) {
1419 if (l->inset == "matrix") {
1420 cell->push_back(createInsetMath(name));
1421 parse2(cell->back(), FLAG_END, mode, false);
1422 } else if (l->inset == "split") {
1423 docstring const valign = parse_verbatim_option() + 'c';
1424 cell->push_back(MathAtom(new InsetMathSplit(name, (char)valign[0])));
1425 parse2(cell->back(), FLAG_END, mode, false);
1428 if (!(mode_ & Parse::QUIET)) {
1430 lyxerr << "found math environment `"
1432 << "' in symbols file with unsupported inset `"
1433 << to_utf8(l->inset)
1436 // create generic environment inset
1437 cell->push_back(MathAtom(new InsetMathEnv(name)));
1438 parse(cell->back().nucleus()->cell(0), FLAG_END, mode);
1444 if (!(mode_ & Parse::QUIET)) {
1446 lyxerr << "found unknown math environment '"
1447 << to_utf8(name) << "'" << endl;
1449 // create generic environment inset
1450 cell->push_back(MathAtom(new InsetMathEnv(name)));
1451 parse(cell->back().nucleus()->cell(0), FLAG_END, mode);
1455 else if (t.cs() == "kern") {
1459 Token const & t = getToken();
1465 if (isValidLength(to_utf8(s)))
1468 cell->push_back(MathAtom(new InsetMathKern(s)));
1471 else if (t.cs() == "label") {
1472 // FIXME: This is swallowed in inline formulas
1473 docstring label = parse_verbatim_item();
1476 if (grid.asHullInset()) {
1477 grid.asHullInset()->label(cellrow, label);
1479 cell->push_back(createInsetMath(t.cs()));
1480 cell->push_back(MathAtom(new InsetMathBrace(ar)));
1484 else if (t.cs() == "choose" || t.cs() == "over"
1485 || t.cs() == "atop" || t.cs() == "brace"
1486 || t.cs() == "brack") {
1487 MathAtom at = createInsetMath(t.cs());
1488 at.nucleus()->cell(0) = *cell;
1490 parse(at.nucleus()->cell(1), flags, mode);
1491 cell->push_back(at);
1495 else if (t.cs() == "color") {
1496 docstring const color = parse_verbatim_item();
1497 cell->push_back(MathAtom(new InsetMathColor(true, color)));
1498 parse(cell->back().nucleus()->cell(0), flags, mode);
1502 else if (t.cs() == "textcolor") {
1503 docstring const color = parse_verbatim_item();
1504 cell->push_back(MathAtom(new InsetMathColor(false, color)));
1505 parse(cell->back().nucleus()->cell(0), FLAG_ITEM, InsetMath::TEXT_MODE);
1508 else if (t.cs() == "normalcolor") {
1509 cell->push_back(createInsetMath(t.cs()));
1510 parse(cell->back().nucleus()->cell(0), flags, mode);
1514 else if (t.cs() == "substack") {
1515 cell->push_back(createInsetMath(t.cs()));
1516 parse2(cell->back(), FLAG_ITEM, mode, false);
1519 else if (t.cs() == "xymatrix") {
1520 odocstringstream os;
1521 while (good() && nextToken().cat() != catBegin)
1522 os << getToken().asInput();
1523 cell->push_back(createInsetMath(t.cs() + os.str()));
1524 parse2(cell->back(), FLAG_ITEM, mode, false);
1527 else if (t.cs() == "framebox" || t.cs() == "makebox") {
1528 cell->push_back(createInsetMath(t.cs()));
1529 parse(cell->back().nucleus()->cell(0), FLAG_OPTION, InsetMath::TEXT_MODE);
1530 parse(cell->back().nucleus()->cell(1), FLAG_OPTION, InsetMath::TEXT_MODE);
1531 parse(cell->back().nucleus()->cell(2), FLAG_ITEM, InsetMath::TEXT_MODE);
1534 else if (t.cs() == "tag") {
1535 if (nextToken().character() == '*') {
1537 cell->push_back(createInsetMath(t.cs() + '*'));
1539 cell->push_back(createInsetMath(t.cs()));
1540 parse(cell->back().nucleus()->cell(0), FLAG_ITEM, InsetMath::TEXT_MODE);
1544 else if (t.cs() == "infer") {
1546 parse(ar, FLAG_OPTION, mode);
1547 cell->push_back(createInsetMath(t.cs()));
1548 parse2(cell->back(), FLAG_ITEM, mode, false);
1552 else if (1 && t.cs() == "ar") {
1553 auto_ptr<InsetMathXYArrow> p(new InsetMathXYArrow);
1554 // try to read target
1555 parse(p->cell(0), FLAG_OTPTION, mode);
1556 // try to read label
1557 if (nextToken().cat() == catSuper || nextToken().cat() == catSub) {
1558 p->up_ = nextToken().cat() == catSuper;
1560 parse(p->cell(1), FLAG_ITEM, mode);
1561 //lyxerr << "read label: " << p->cell(1) << endl;
1564 cell->push_back(MathAtom(p.release()));
1565 //lyxerr << "read cell: " << cell << endl;
1569 else if (t.cs() == "lyxmathsym") {
1571 if (getToken().cat() != catBegin) {
1572 error("'{' expected in \\" + t.cs());
1577 CatCode cat = nextToken().cat();
1578 while (good() && (count || cat != catEnd)) {
1579 if (cat == catBegin)
1581 else if (cat == catEnd)
1583 cmd += getToken().asInput();
1584 cat = nextToken().cat();
1586 if (getToken().cat() != catEnd) {
1587 error("'}' expected in \\" + t.cs());
1591 cmd = Encodings::fromLaTeXCommand(cmd, rem);
1592 for (size_t i = 0; i < cmd.size(); ++i)
1593 cell->push_back(MathAtom(new InsetMathChar(cmd[i])));
1595 MathAtom at = createInsetMath(t.cs());
1596 cell->push_back(at);
1598 if (!mathed_parse_cell(ar, '{' + rem + '}', mode_))
1604 else if (t.cs().size()) {
1605 latexkeys const * l = in_word_set(t.cs());
1607 if (l->inset == "big") {
1609 docstring const delim = getToken().asInput();
1610 if (InsetMathBig::isBigInsetDelim(delim))
1611 cell->push_back(MathAtom(
1612 new InsetMathBig(t.cs(), delim)));
1614 cell->push_back(createInsetMath(t.cs()));
1619 else if (l->inset == "font") {
1620 cell->push_back(createInsetMath(t.cs()));
1621 parse(cell->back().nucleus()->cell(0),
1622 FLAG_ITEM, asMode(mode, l->extra));
1625 else if (l->inset == "oldfont") {
1626 cell->push_back(createInsetMath(t.cs()));
1627 parse(cell->back().nucleus()->cell(0),
1628 flags | FLAG_ALIGN, asMode(mode, l->extra));
1629 if (prevToken().cat() != catAlign &&
1630 prevToken().cs() != "\\")
1635 else if (l->inset == "style") {
1636 cell->push_back(createInsetMath(t.cs()));
1637 parse(cell->back().nucleus()->cell(0),
1638 flags | FLAG_ALIGN, mode);
1639 if (prevToken().cat() != catAlign &&
1640 prevToken().cs() != "\\")
1646 MathAtom at = createInsetMath(t.cs());
1647 for (InsetMath::idx_type i = 0; i < at->nargs(); ++i)
1648 parse(at.nucleus()->cell(i),
1649 FLAG_ITEM, asMode(mode, l->extra));
1650 cell->push_back(at);
1655 bool is_unicode_symbol = false;
1656 if (mode == InsetMath::TEXT_MODE) {
1658 docstring cmd = prevToken().asInput();
1660 CatCode cat = nextToken().cat();
1661 if (cat == catBegin) {
1663 while (good() && (count || cat != catEnd)) {
1664 cat = nextToken().cat();
1665 cmd += getToken().asInput();
1667 if (cat == catBegin)
1669 else if (cat == catEnd)
1675 Encodings::fromLaTeXCommand(cmd, is_combining);
1677 if (cat == catLetter)
1679 cmd += getToken().asInput();
1681 if (cat == catLetter)
1683 c = Encodings::fromLaTeXCommand(cmd, is_combining);
1686 is_unicode_symbol = true;
1687 cell->push_back(MathAtom(new InsetMathChar(c)));
1689 while (num_tokens--)
1693 if (!is_unicode_symbol) {
1694 MathAtom at = createInsetMath(t.cs());
1695 InsetMath::mode_type m = mode;
1696 //if (m == InsetMath::UNDECIDED_MODE)
1697 //lyxerr << "default creation: m1: " << m << endl;
1698 if (at->currentMode() != InsetMath::UNDECIDED_MODE)
1699 m = at->currentMode();
1700 //lyxerr << "default creation: m2: " << m << endl;
1701 InsetMath::idx_type start = 0;
1702 // this fails on \bigg[...\bigg]
1704 //parse(opt, FLAG_OPTION, InsetMath::VERBATIM_MODE);
1707 // at.nucleus()->cell(0) = opt;
1709 for (InsetMath::idx_type i = start; i < at->nargs(); ++i) {
1710 parse(at.nucleus()->cell(i), FLAG_ITEM, m);
1713 cell->push_back(at);
1719 if (flags & FLAG_LEAVE) {
1720 flags &= ~FLAG_LEAVE;
1729 } // anonymous namespace
1732 bool mathed_parse_cell(MathData & ar, docstring const & str, Parse::flags f)
1734 return Parser(str, f).parse(ar, 0, f & Parse::TEXTMODE ?
1735 InsetMath::TEXT_MODE : InsetMath::MATH_MODE);
1739 bool mathed_parse_cell(MathData & ar, istream & is, Parse::flags f)
1741 return Parser(is, f).parse(ar, 0, f & Parse::TEXTMODE ?
1742 InsetMath::TEXT_MODE : InsetMath::MATH_MODE);
1746 bool mathed_parse_normal(MathAtom & t, docstring const & str, Parse::flags f)
1748 return Parser(str, f).parse(t);
1752 bool mathed_parse_normal(MathAtom & t, Lexer & lex, Parse::flags f)
1754 return Parser(lex, f).parse(t);
1758 bool mathed_parse_normal(InsetMathGrid & grid, docstring const & str, Parse::flags f)
1760 return Parser(str, f).parse1(grid, 0, f & Parse::TEXTMODE ?
1761 InsetMath::TEXT_MODE : InsetMath::MATH_MODE, false);
1767 fill(theCatcode, theCatcode + 128, catOther);
1768 fill(theCatcode + 'a', theCatcode + 'z' + 1, catLetter);
1769 fill(theCatcode + 'A', theCatcode + 'Z' + 1, catLetter);
1771 theCatcode[int('\\')] = catEscape;
1772 theCatcode[int('{')] = catBegin;
1773 theCatcode[int('}')] = catEnd;
1774 theCatcode[int('$')] = catMath;
1775 theCatcode[int('&')] = catAlign;
1776 theCatcode[int('\n')] = catNewline;
1777 theCatcode[int('#')] = catParameter;
1778 theCatcode[int('^')] = catSuper;
1779 theCatcode[int('_')] = catSub;
1780 theCatcode[int(0x7f)] = catIgnore;
1781 theCatcode[int(' ')] = catSpace;
1782 theCatcode[int('\t')] = catSpace;
1783 theCatcode[int('\r')] = catNewline;
1784 theCatcode[int('~')] = catActive;
1785 theCatcode[int('%')] = catComment;