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 "InsetMathCancelto.h"
46 #include "InsetMathChar.h"
47 #include "InsetMathColor.h"
48 #include "InsetMathComment.h"
49 #include "InsetMathDelim.h"
50 #include "InsetMathEnsureMath.h"
51 #include "InsetMathEnv.h"
52 #include "InsetMathFrac.h"
53 #include "InsetMathKern.h"
54 #include "MathMacro.h"
55 #include "InsetMathPar.h"
56 #include "InsetMathRef.h"
57 #include "InsetMathRoot.h"
58 #include "InsetMathScript.h"
59 #include "InsetMathSideset.h"
60 #include "InsetMathSpace.h"
61 #include "InsetMathSplit.h"
62 #include "InsetMathSqrt.h"
63 #include "InsetMathStackrel.h"
64 #include "InsetMathString.h"
65 #include "InsetMathTabular.h"
66 #include "MathMacroTemplate.h"
67 #include "MathFactory.h"
68 #include "MathMacroArgument.h"
69 #include "MathSupport.h"
72 #include "BufferParams.h"
76 #include "support/debug.h"
77 #include "support/convert.h"
78 #include "support/docstream.h"
90 InsetMath::mode_type asMode(InsetMath::mode_type oldmode, docstring const & str)
92 //lyxerr << "handling mode: '" << str << "'" << endl;
93 if (str == "mathmode")
94 return InsetMath::MATH_MODE;
95 if (str == "textmode" || str == "forcetext")
96 return InsetMath::TEXT_MODE;
101 bool stared(docstring const & s)
103 size_t const n = s.size();
104 return n && s[n - 1] == '*';
108 docstring const repl(docstring const & oldstr, char_type const c,
109 docstring const & macro, bool textmode = false)
115 for (i = 0, j = 0; i < oldstr.size(); ++i) {
116 if (c == oldstr[i]) {
117 newstr.append(oldstr, j, i - j);
118 newstr.append(macro);
120 if (macro.size() > 2 && j < oldstr.size())
121 newstr += (textmode && oldstr[j] == ' ' ? '\\' : ' ');
129 newstr.append(oldstr, j, i - j);
134 docstring escapeSpecialChars(docstring const & str, bool textmode)
136 docstring const backslash = textmode ? from_ascii("\\textbackslash")
137 : from_ascii("\\backslash");
138 docstring const caret = textmode ? from_ascii("\\textasciicircum")
139 : from_ascii("\\mathcircumflex");
140 docstring const tilde = textmode ? from_ascii("\\textasciitilde")
141 : from_ascii("\\sim");
143 return repl(repl(repl(repl(repl(repl(repl(repl(repl(repl(str,
144 '\\', backslash, textmode),
145 '^', caret, textmode),
146 '~', tilde, textmode),
147 '_', from_ascii("\\_")),
148 '$', from_ascii("\\$")),
149 '#', from_ascii("\\#")),
150 '&', from_ascii("\\&")),
151 '%', from_ascii("\\%")),
152 '{', from_ascii("\\{")),
153 '}', from_ascii("\\}"));
158 * Add the row \p cellrow to \p grid.
159 * \returns wether the row could be added. Adding a row can fail for
160 * environments like "equation" that have a fixed number of rows.
162 bool addRow(InsetMathGrid & grid, InsetMathGrid::row_type & cellrow,
163 docstring const & vskip, bool allow_newpage_ = true)
166 if (cellrow == grid.nrows()) {
167 //lyxerr << "adding row " << cellrow << endl;
168 grid.addRow(cellrow - 1);
169 if (cellrow == grid.nrows()) {
170 // We can't add a row 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 row";
179 lyxerr << " with extra space " << to_utf8(vskip);
181 lyxerr << " with no page break allowed";
182 lyxerr << '.' << endl;
186 grid.vcrskip(Length(to_utf8(vskip)), cellrow - 1);
187 grid.rowinfo(cellrow - 1).allow_newpage_ = allow_newpage_;
193 * Add the column \p cellcol to \p grid.
194 * \returns wether the column could be added. Adding a column can fail for
195 * environments like "eqnarray" that have a fixed number of columns.
197 bool addCol(InsetMathGrid & grid, InsetMathGrid::col_type & cellcol)
200 if (cellcol == grid.ncols()) {
201 //lyxerr << "adding column " << cellcol << endl;
202 grid.addCol(cellcol);
203 if (cellcol == grid.ncols()) {
204 // We can't add a column to this grid, so let's
205 // append the content of this cell to the previous
207 // This does not happen in well formed .lyx files,
208 // but LyX versions 1.3.x and older could create
209 // such files and tex2lyx can still do that.
211 lyxerr << "ignoring extra column." << endl;
220 * Check whether the last row is empty and remove it if yes.
221 * Otherwise the following code
229 * will result in a grid with 3 rows (+ the dummy row that is always present),
230 * because the last '\\' opens a new row.
231 * Note that this is only needed for inner-hull grid types, such as array
232 * or aligned, but not for outer-hull grid types, such as eqnarray or align.
234 void delEmptyLastRow(InsetMathGrid & grid)
236 InsetMathGrid::row_type const row = grid.nrows() - 1;
237 for (InsetMathGrid::col_type col = 0; col < grid.ncols(); ++col) {
238 if (!grid.cell(grid.index(row, col)).empty())
241 // Copy the row information of the empty row (which would contain the
242 // last hline in the example above) to the dummy row and delete the
244 grid.rowinfo(row + 1) = grid.rowinfo(row);
250 * Tell whether the environment name corresponds to an inner-hull grid type.
252 bool innerHull(docstring const & name)
254 // For [bB]matrix, [vV]matrix, and pmatrix we can check the suffix only
255 return name == "array" || name == "cases" || name == "aligned"
256 || name == "alignedat" || name == "gathered" || name == "split"
257 || name == "subarray" || name == "tabular" || name == "matrix"
258 || name == "smallmatrix" || name.substr(1) == "matrix";
262 // These are TeX's catcodes
264 catEscape, // 0 backslash
274 catSpace, // 10 space
275 catLetter, // 11 a-zA-Z
276 catOther, // 12 none of the above
279 catInvalid // 15 <delete>
282 CatCode theCatcode[128];
285 inline CatCode catcode(char_type c)
287 /* The only characters that are not catOther lie in the pure ASCII
288 * range. Therefore theCatcode has only 128 entries.
289 * TeX itself deals with 8bit characters, so if needed this table
290 * could be enlarged to 256 entries.
291 * Any larger value does not make sense, since the fact that we use
292 * unicode internally does not change Knuth's TeX engine.
293 * Apart from that a table for the full 21bit UCS4 range would waste
294 * too much memory. */
298 return theCatcode[c];
303 FLAG_ALIGN = 1 << 0, // next & or \\ ends the parsing process
304 FLAG_BRACE_LAST = 1 << 1, // next closing brace ends the parsing
305 FLAG_RIGHT = 1 << 2, // next \\right ends the parsing process
306 FLAG_END = 1 << 3, // next \\end ends the parsing process
307 FLAG_BRACK_LAST = 1 << 4, // next closing bracket ends the parsing
308 FLAG_TEXTMODE = 1 << 5, // we are in a box
309 FLAG_ITEM = 1 << 6, // read a (possibly braced) token
310 FLAG_LEAVE = 1 << 7, // leave the loop at the end
311 FLAG_SIMPLE = 1 << 8, // next $ leaves the loop
312 FLAG_EQUATION = 1 << 9, // next \] leaves the loop
313 FLAG_SIMPLE2 = 1 << 10, // next \) leaves the loop
314 FLAG_OPTION = 1 << 11, // read [...] style option
315 FLAG_BRACED = 1 << 12 // read {...} style argument
320 // Helper class for parsing
326 Token() : cs_(), char_(0), cat_(catIgnore) {}
328 Token(char_type c, CatCode cat) : cs_(), char_(c), cat_(cat) {}
330 explicit Token(docstring const & cs) : cs_(cs), char_(0), cat_(catIgnore) {}
333 docstring const & cs() const { return cs_; }
335 CatCode cat() const { return cat_; }
337 char_type character() const { return char_; }
339 docstring asString() const { return !cs_.empty() ? cs_ : docstring(1, char_); }
341 docstring asInput() const { return !cs_.empty() ? '\\' + cs_ : docstring(1, char_); }
353 ostream & operator<<(ostream & os, Token const & t)
355 if (!t.cs().empty()) {
356 docstring const & cs = t.cs();
357 // FIXME: For some strange reason, the stream operator instanciate
358 // a new Token before outputting the contents of t.cs().
359 // Because of this the line
361 // below becomes recursive.
362 // In order to avoid that we return early:
365 os << '\\' << to_utf8(cs);
367 else if (t.cat() == catLetter)
370 os << '[' << t.character() << ',' << t.cat() << ']';
378 typedef InsetMath::mode_type mode_type;
380 typedef Parse::flags parse_mode;
383 Parser(Lexer & lex, parse_mode mode, Buffer * buf);
384 /// Only use this for reading from .lyx file format, for the reason
385 /// see Parser::tokenize(istream &).
386 Parser(istream & is, parse_mode mode, Buffer * buf);
388 Parser(docstring const & str, parse_mode mode, Buffer * buf);
391 bool parse(MathAtom & at);
393 bool parse(MathData & array, unsigned flags, mode_type mode);
395 bool parse1(InsetMathGrid & grid, unsigned flags, mode_type mode,
398 MathData parse(unsigned flags, mode_type mode);
400 int lineno() const { return lineno_; }
403 /// store current position
405 /// restore previous position
407 /// forget last saved position
412 void parse2(MathAtom & at, unsigned flags, mode_type mode, bool numbered);
413 /// get arg delimited by 'left' and 'right'
414 docstring getArg(char_type left, char_type right);
418 void error(string const & msg);
419 void error(docstring const & msg) { error(to_utf8(msg)); }
420 /// dump contents to screen
422 /// Only use this for reading from .lyx file format (see
423 /// implementation for reason)
424 void tokenize(istream & is);
426 void tokenize(docstring const & s);
428 void skipSpaceTokens(idocstream & is, char_type c);
430 void push_back(Token const & t);
434 Token const & prevToken() const;
436 Token const & nextToken() const;
438 Token const & getToken();
439 /// skips spaces if any
442 void lex(docstring const & s);
446 docstring parse_verbatim_item();
448 docstring parse_verbatim_option();
453 vector<Token> tokens_;
457 std::vector<unsigned> positions_;
458 /// Stack of active environments
459 vector<docstring> environments_;
469 Parser::Parser(Lexer & lexer, parse_mode mode, Buffer * buf)
470 : lineno_(lexer.lineNumber()), pos_(0), mode_(mode), success_(true),
473 tokenize(lexer.getStream());
478 Parser::Parser(istream & is, parse_mode mode, Buffer * buf)
479 : lineno_(0), pos_(0), mode_(mode), success_(true), buffer_(buf)
485 Parser::Parser(docstring const & str, parse_mode mode, Buffer * buf)
486 : lineno_(0), pos_(0), mode_(mode), success_(true), buffer_(buf)
492 void Parser::push_back(Token const & t)
494 tokens_.push_back(t);
498 void Parser::pop_back()
504 Token const & Parser::prevToken() const
506 static const Token dummy;
507 return pos_ > 0 ? tokens_[pos_ - 1] : dummy;
511 Token const & Parser::nextToken() const
513 static const Token dummy;
514 return good() ? tokens_[pos_] : dummy;
518 Token const & Parser::getToken()
520 static const Token dummy;
521 //lyxerr << "looking at token " << tokens_[pos_] << " pos: " << pos_ << endl;
522 return good() ? tokens_[pos_++] : dummy;
526 void Parser::skipSpaces()
528 while (nextToken().cat() == catSpace || nextToken().cat() == catNewline)
533 void Parser::putback()
539 void Parser::pushPosition()
541 positions_.push_back(pos_);
545 void Parser::popPosition()
547 pos_ = positions_.back();
548 positions_.pop_back();
552 void Parser::dropPosition()
554 positions_.pop_back();
558 bool Parser::good() const
560 return pos_ < tokens_.size();
564 char_type Parser::getChar()
567 error("The input stream is not well...");
570 return tokens_[pos_++].character();
574 docstring Parser::getArg(char_type left, char_type right)
582 char_type c = getChar();
587 while ((c = getChar()) != right && good())
594 void Parser::skipSpaceTokens(idocstream & is, char_type c)
596 // skip trailing spaces
597 while (catcode(c) == catSpace || catcode(c) == catNewline)
600 //lyxerr << "putting back: " << c << endl;
605 void Parser::tokenize(istream & is)
607 // eat everything up to the next \end_inset or end of stream
608 // and store it in s for further tokenization
613 if (s.size() >= 10 && s.substr(s.size() - 10) == "\\end_inset") {
614 s = s.substr(0, s.size() - 10);
618 // Remove the space after \end_inset
619 if (is.get(c) && c != ' ')
623 tokenize(from_utf8(s));
627 void Parser::tokenize(docstring const & buffer)
629 idocstringstream is(mode_ & Parse::VERBATIM
630 ? escapeSpecialChars(buffer, mode_ & Parse::TEXTMODE)
631 : buffer, ios::in | ios::binary);
635 //lyxerr << "reading c: " << c << endl;
637 switch (catcode(c)) {
641 if (catcode(c) == catNewline)
642 ; //push_back(Token("par"));
644 push_back(Token('\n', catNewline));
652 while (is.get(c) && catcode(c) != catNewline)
662 error("unexpected end of input");
667 if (catcode(c) == catLetter) {
669 while (is.get(c) && catcode(c) == catLetter)
671 skipSpaceTokens(is, c);
680 push_back(Token(c, catcode(c)));
682 skipSpaceTokens(is, c);
687 if (!(mode_ & Parse::QUIET))
688 lyxerr << "ignoring a char: " << int(c) << endl;
693 push_back(Token(c, catcode(c)));
703 void Parser::dump() const
705 lyxerr << "\nTokens: ";
706 for (unsigned i = 0; i < tokens_.size(); ++i) {
709 lyxerr << tokens_[i];
711 lyxerr << " pos: " << pos_ << endl;
715 void Parser::error(string const & msg)
718 if (!(mode_ & Parse::QUIET)) {
719 lyxerr << "Line ~" << lineno_ << ": Math parse error: "
726 bool Parser::parse(MathAtom & at)
729 MathData ar(buffer_);
730 parse(ar, false, InsetMath::UNDECIDED_MODE);
731 if (ar.size() != 1 || ar.front()->getType() == hullNone) {
732 if (!(mode_ & Parse::QUIET))
733 lyxerr << "unusual contents found: " << ar << endl;
734 at = MathAtom(new InsetMathPar(buffer_, ar));
735 //if (at->nargs() > 0)
736 // at.nucleus()->cell(0) = ar;
738 // lyxerr << "unusual contents found: " << ar << endl;
746 docstring Parser::parse_verbatim_option()
750 if (nextToken().character() == '[') {
751 Token t = getToken();
752 for (Token t = getToken(); t.character() != ']' && good(); t = getToken()) {
753 if (t.cat() == catBegin) {
755 res += '{' + parse_verbatim_item() + '}';
764 docstring Parser::parse_verbatim_item()
768 if (nextToken().cat() == catBegin) {
769 Token t = getToken();
770 for (Token t = getToken(); t.cat() != catEnd && good(); t = getToken()) {
771 if (t.cat() == catBegin) {
773 res += '{' + parse_verbatim_item() + '}';
783 MathData Parser::parse(unsigned flags, mode_type mode)
785 MathData ar(buffer_);
786 parse(ar, flags, mode);
791 bool Parser::parse(MathData & array, unsigned flags, mode_type mode)
793 InsetMathGrid grid(buffer_, 1, 1);
794 parse1(grid, flags, mode, false);
795 array = grid.cell(0);
800 void Parser::parse2(MathAtom & at, const unsigned flags, const mode_type mode,
803 parse1(*(at.nucleus()->asGridInset()), flags, mode, numbered);
807 bool Parser::parse1(InsetMathGrid & grid, unsigned flags,
808 const mode_type mode, const bool numbered)
811 InsetMathGrid::row_type cellrow = 0;
812 InsetMathGrid::col_type cellcol = 0;
813 MathData * cell = &grid.cell(grid.index(cellrow, cellcol));
814 Buffer * buf = buffer_;
816 if (grid.asHullInset())
817 grid.asHullInset()->numbered(cellrow, numbered);
820 //lyxerr << " flags: " << flags << endl;
821 //lyxerr << " mode: " << mode << endl;
822 //lyxerr << "grid: " << grid << endl;
825 Token const & t = getToken();
828 lyxerr << "t: " << t << " flags: " << flags << endl;
829 lyxerr << "mode: " << mode << endl;
834 if (flags & FLAG_ITEM) {
836 if (t.cat() == catBegin) {
837 // skip the brace and collect everything to the next matching
839 parse1(grid, FLAG_BRACE_LAST, mode, numbered);
843 // handle only this single token, leave the loop if done
848 if (flags & FLAG_BRACED) {
849 if (t.cat() == catSpace)
852 if (t.cat() != catBegin) {
853 error("opening brace expected");
857 // skip the brace and collect everything to the next matching
859 flags = FLAG_BRACE_LAST;
863 if (flags & FLAG_OPTION) {
864 if (t.cat() == catOther && t.character() == '[') {
866 parse(ar, FLAG_BRACK_LAST, mode);
869 // no option found, put back token and we are done
878 if (t.cat() == catMath) {
879 if (mode != InsetMath::MATH_MODE) {
880 // we are inside some text mode thingy, so opening new math is allowed
881 Token const & n = getToken();
882 if (n.cat() == catMath) {
883 // TeX's $$...$$ syntax for displayed math
884 if (mode == InsetMath::UNDECIDED_MODE) {
885 cell->push_back(MathAtom(new InsetMathHull(buf, hullEquation)));
886 parse2(cell->back(), FLAG_SIMPLE, InsetMath::MATH_MODE, false);
887 getToken(); // skip the second '$' token
889 // This is not an outer hull and display math is
890 // not allowed inside text mode environments.
891 error("bad math environment $$");
895 // simple $...$ stuff
897 if (mode == InsetMath::UNDECIDED_MODE) {
898 cell->push_back(MathAtom(new InsetMathHull(buf, hullSimple)));
899 parse2(cell->back(), FLAG_SIMPLE, InsetMath::MATH_MODE, false);
901 // Don't create nested math hulls (bug #5392)
902 cell->push_back(MathAtom(new InsetMathEnsureMath(buf)));
903 parse(cell->back().nucleus()->cell(0), FLAG_SIMPLE, InsetMath::MATH_MODE);
908 else if (flags & FLAG_SIMPLE) {
909 // this is the end of the formula
914 Token const & n = getToken();
915 if (n.cat() == catMath) {
916 error("something strange in the parser");
919 // This is inline math ($...$), but the parser thinks we are
920 // already in math mode and latex would issue an error, unless we
921 // are inside a text mode user macro. We have no way to tell, so
922 // let's play safe by using \ensuremath, as it will work in any case.
924 cell->push_back(MathAtom(new InsetMathEnsureMath(buf)));
925 parse(cell->back().nucleus()->cell(0), FLAG_SIMPLE, InsetMath::MATH_MODE);
930 else if (t.cat() == catLetter)
931 cell->push_back(MathAtom(new InsetMathChar(t.character())));
933 else if (t.cat() == catSpace && mode != InsetMath::MATH_MODE) {
934 if (cell->empty() || cell->back()->getChar() != ' ')
935 cell->push_back(MathAtom(new InsetMathChar(t.character())));
938 else if (t.cat() == catNewline && mode != InsetMath::MATH_MODE) {
939 if (cell->empty() || cell->back()->getChar() != ' ')
940 cell->push_back(MathAtom(new InsetMathChar(' ')));
943 else if (t.cat() == catParameter) {
944 Token const & n = getToken();
945 cell->push_back(MathAtom(new MathMacroArgument(n.character()-'0')));
948 else if (t.cat() == catActive)
949 cell->push_back(MathAtom(new InsetMathSpace(string(1, t.character()), "")));
951 else if (t.cat() == catBegin) {
953 parse(ar, FLAG_BRACE_LAST, mode);
954 // do not create a BraceInset if they were written by LyX
955 // this helps to keep the annoyance of "a choose b" to a minimum
956 if (ar.size() == 1 && ar[0]->extraBraces())
959 cell->push_back(MathAtom(new InsetMathBrace(ar)));
962 else if (t.cat() == catEnd) {
963 if (flags & FLAG_BRACE_LAST)
965 error("found '}' unexpectedly");
966 //LASSERT(false, /**/);
967 //add(cell, '}', LM_TC_TEX);
970 else if (t.cat() == catAlign) {
971 //lyxerr << " column now " << (cellcol + 1)
972 // << " max: " << grid.ncols() << endl;
973 if (flags & FLAG_ALIGN)
975 if (addCol(grid, cellcol))
976 cell = &grid.cell(grid.index(cellrow, cellcol));
979 else if (t.cat() == catSuper || t.cat() == catSub) {
980 bool up = (t.cat() == catSuper);
981 // we need no new script inset if the last thing was a scriptinset,
982 // which has that script already not the same script already
984 cell->push_back(MathAtom(new InsetMathScript(buf, up)));
985 else if (cell->back()->asScriptInset() &&
986 !cell->back()->asScriptInset()->has(up))
987 cell->back().nucleus()->asScriptInset()->ensure(up);
988 else if (cell->back()->asScriptInset())
989 cell->push_back(MathAtom(new InsetMathScript(buf, up)));
991 cell->back() = MathAtom(new InsetMathScript(buf, cell->back(), up));
992 InsetMathScript * p = cell->back().nucleus()->asScriptInset();
993 // special handling of {}-bases
994 // Here we could remove the brace inset for things
995 // like {a'}^2 and add the braces back in
996 // InsetMathScript::write().
997 // We do not do it, since it is not possible to detect
998 // reliably whether the braces are needed because the
999 // nucleus contains more than one symbol, or whether
1000 // they are needed for unknown commands like \xx{a}_0
1001 // or \yy{a}{b}_0. This was done in revision 14819
1002 // in an unreliable way. See this thread
1003 // http://www.mail-archive.com/lyx-devel%40lists.lyx.org/msg104917.html
1004 // for more details.
1005 // However, we remove empty braces because they look
1006 // ugly on screen and we are sure that they were added
1007 // by the write() method (and will be re-added on save).
1008 if (p->nuc().size() == 1 &&
1009 p->nuc().back()->asBraceInset() &&
1010 p->nuc().back()->asBraceInset()->cell(0).empty())
1013 parse(p->cell(p->idxOfScript(up)), FLAG_ITEM, mode);
1020 else if (t.character() == ']' && (flags & FLAG_BRACK_LAST)) {
1021 //lyxerr << "finished reading option" << endl;
1025 else if (t.cat() == catOther) {
1026 char_type c = t.character();
1027 if (isAsciiOrMathAlpha(c)
1028 || mode_ & Parse::VERBATIM
1029 || !(mode_ & Parse::USETEXT)
1030 || mode == InsetMath::TEXT_MODE) {
1031 cell->push_back(MathAtom(new InsetMathChar(c)));
1033 MathAtom at = createInsetMath("text", buf);
1034 at.nucleus()->cell(0).push_back(MathAtom(new InsetMathChar(c)));
1035 while (nextToken().cat() == catOther
1036 && !isAsciiOrMathAlpha(nextToken().character())) {
1037 c = getToken().character();
1038 at.nucleus()->cell(0).push_back(MathAtom(new InsetMathChar(c)));
1040 cell->push_back(at);
1044 else if (t.cat() == catComment) {
1047 Token const & t = getToken();
1048 if (t.cat() == catNewline)
1052 cell->push_back(MathAtom(new InsetMathComment(buf, s)));
1057 // control sequences
1060 else if (t.cs() == "lyxlock") {
1062 cell->back().nucleus()->lock(true);
1065 else if ((t.cs() == "global" && nextToken().cs() == "def") ||
1067 if (t.cs() == "global")
1071 docstring name = getToken().cs();
1076 while (good() && nextToken().cat() != catBegin) {
1077 pars += getToken().cs();
1084 parse(def, FLAG_ITEM, InsetMath::UNDECIDED_MODE);
1086 // is a version for display attached?
1089 if (nextToken().cat() == catBegin)
1090 parse(display, FLAG_ITEM, InsetMath::MATH_MODE);
1092 cell->push_back(MathAtom(new MathMacroTemplate(buf,
1093 name, nargs, 0, MacroTypeDef,
1094 vector<MathData>(), def, display)));
1096 if (buf && (mode_ & Parse::TRACKMACRO))
1097 buf->usermacros.insert(name);
1100 else if (t.cs() == "newcommand" ||
1101 t.cs() == "renewcommand" ||
1102 t.cs() == "newlyxcommand") {
1104 if (getToken().cat() != catBegin) {
1105 error("'{' in \\newcommand expected (1) ");
1108 docstring name = getToken().cs();
1109 if (getToken().cat() != catEnd) {
1110 error("'}' in \\newcommand expected");
1115 docstring const arg = getArg('[', ']');
1118 nargs = convert<int>(arg);
1120 // optional argument given?
1123 vector<MathData> optionalValues;
1124 while (nextToken().character() == '[') {
1126 optionalValues.push_back(MathData());
1127 parse(optionalValues[optionals], FLAG_BRACK_LAST, mode);
1132 parse(def, FLAG_ITEM, InsetMath::UNDECIDED_MODE);
1134 // is a version for display attached?
1137 if (nextToken().cat() == catBegin)
1138 parse(display, FLAG_ITEM, InsetMath::MATH_MODE);
1140 cell->push_back(MathAtom(new MathMacroTemplate(buf,
1141 name, nargs, optionals, MacroTypeNewcommand,
1142 optionalValues, def, display)));
1144 if (buf && (mode_ & Parse::TRACKMACRO))
1145 buf->usermacros.insert(name);
1148 else if (t.cs() == "newcommandx" ||
1149 t.cs() == "renewcommandx") {
1150 // \newcommandx{\foo}[2][usedefault, addprefix=\global,1=default]{#1,#2}
1153 if (nextToken().cat() == catBegin) {
1155 name = getToken().cs();
1156 if (getToken().cat() != catEnd) {
1157 error("'}' in \\newcommandx expected");
1161 name = getToken().cs();
1164 docstring const arg = getArg('[', ']');
1166 error("[num] in \\newcommandx expected");
1169 int nargs = convert<int>(arg);
1173 vector<MathData> optionalValues;
1174 if (nextToken().character() == '[') {
1178 // handle 'opt=value' options, separated by ','.
1180 while (nextToken().character() != ']' && good()) {
1181 if (nextToken().character() >= '1'
1182 && nextToken().character() <= '9') {
1183 // optional value -> get parameter number
1184 int n = getChar() - '0';
1186 error("Arity of \\newcommandx too low "
1187 "for given optional parameter.");
1192 if (getToken().character() != '=') {
1193 error("'=' and optional parameter value "
1194 "expected for \\newcommandx");
1199 int optNum = max(size_t(n), optionalValues.size());
1200 optionalValues.resize(optNum);
1201 optionalValues[n - 1].clear();
1202 while (nextToken().character() != ']'
1203 && nextToken().character() != ',') {
1205 parse(data, FLAG_ITEM, InsetMath::UNDECIDED_MODE);
1206 optionalValues[n - 1].append(data);
1208 optionals = max(n, optionals);
1209 } else if (nextToken().cat() == catLetter) {
1210 // we in fact ignore every non-optional
1215 while (nextToken().cat() == catLetter)
1221 if (nextToken().character() == '=') {
1223 while (nextToken().character() != ']'
1224 && nextToken().character() != ',')
1225 parse(value, FLAG_ITEM,
1226 InsetMath::UNDECIDED_MODE);
1229 error("option for \\newcommandx expected");
1235 if (nextToken().character() == ',') {
1238 } else if (nextToken().character() != ']') {
1239 error("Expecting ',' or ']' in options "
1240 "of \\newcommandx");
1253 parse(def, FLAG_ITEM, InsetMath::UNDECIDED_MODE);
1255 // is a version for display attached?
1258 if (nextToken().cat() == catBegin)
1259 parse(display, FLAG_ITEM, InsetMath::MATH_MODE);
1261 cell->push_back(MathAtom(new MathMacroTemplate(buf,
1262 name, nargs, optionals, MacroTypeNewcommandx,
1263 optionalValues, def, display)));
1265 if (buf && (mode_ & Parse::TRACKMACRO))
1266 buf->usermacros.insert(name);
1269 else if (t.cs() == "(") {
1270 if (mode == InsetMath::UNDECIDED_MODE) {
1271 cell->push_back(MathAtom(new InsetMathHull(buf, hullSimple)));
1272 parse2(cell->back(), FLAG_SIMPLE2, InsetMath::MATH_MODE, false);
1274 // Don't create nested math hulls (bug #5392)
1275 cell->push_back(MathAtom(new InsetMathEnsureMath(buf)));
1276 parse(cell->back().nucleus()->cell(0), FLAG_SIMPLE2, InsetMath::MATH_MODE);
1280 else if (t.cs() == "[") {
1281 if (mode != InsetMath::UNDECIDED_MODE) {
1282 error("bad math environment [");
1285 cell->push_back(MathAtom(new InsetMathHull(buf, hullEquation)));
1286 parse2(cell->back(), FLAG_EQUATION, InsetMath::MATH_MODE, false);
1289 else if (t.cs() == "protect")
1290 // ignore \\protect, will hopefully be re-added during output
1293 else if (t.cs() == "end") {
1294 if (flags & FLAG_END) {
1295 // eat environment name
1296 docstring const name = getArg('{', '}');
1297 if (environments_.empty())
1298 error("'found \\end{" + name +
1299 "}' without matching '\\begin{" +
1301 else if (name != environments_.back())
1302 error("'\\end{" + name +
1303 "}' does not match '\\begin{" +
1304 environments_.back() + "}'");
1306 environments_.pop_back();
1307 // Delete empty last row in matrix
1309 // If you abuse InsetMathGrid for
1310 // non-matrix like structures you
1311 // probably need to refine this test.
1312 // Right now we only have to test for
1313 // single line hull insets.
1314 if (grid.nrows() > 1 && innerHull(name))
1315 delEmptyLastRow(grid);
1319 error("found 'end' unexpectedly");
1322 else if (t.cs() == ")") {
1323 if (flags & FLAG_SIMPLE2)
1325 error("found '\\)' unexpectedly");
1328 else if (t.cs() == "]") {
1329 if (flags & FLAG_EQUATION)
1331 error("found '\\]' unexpectedly");
1334 else if (t.cs() == "\\") {
1335 if (flags & FLAG_ALIGN)
1338 if (nextToken().asInput() == "*") {
1340 added = addRow(grid, cellrow, docstring(), false);
1342 // skip "{}" added in front of "[" (the
1343 // counterpart is in InsetMathGrid::eolString())
1344 // skip spaces because formula could come from tex2lyx
1345 bool skipBraces = false;
1348 if (nextToken().cat() == catBegin) {
1351 if (nextToken().cat() == catEnd) {
1354 if (nextToken().asInput() == "[")
1365 arg = getArg('[', ']');
1366 added = addRow(grid, cellrow, arg);
1368 error("missing token after \\\\");
1372 if (grid.asHullInset())
1373 grid.asHullInset()->numbered(
1375 cell = &grid.cell(grid.index(cellrow,
1381 else if (t.cs() == "multicolumn") {
1382 // extract column count and insert dummy cells
1384 parse(count, FLAG_ITEM, mode);
1386 if (!extractNumber(count, cols)) {
1388 lyxerr << " can't extract number of cells from " << count << endl;
1390 // resize the table if necessary
1391 for (int i = 0; i < cols; ++i) {
1392 if (addCol(grid, cellcol)) {
1393 cell = &grid.cell(grid.index(
1395 // mark this as dummy
1396 grid.cellinfo(grid.index(
1397 cellrow, cellcol)).dummy_ = true;
1400 // the last cell is the real thing, not a dummy
1401 grid.cellinfo(grid.index(cellrow, cellcol)).dummy_ = false;
1403 // read special alignment
1405 parse(align, FLAG_ITEM, mode);
1406 //grid.cellinfo(grid.index(cellrow, cellcol)).align_ = extractString(align);
1408 // parse the remaining contents into the "real" cell
1409 parse(*cell, FLAG_ITEM, mode);
1413 else if (t.cs() == "limits" || t.cs() == "nolimits") {
1414 CatCode const cat = nextToken().cat();
1415 if (cat == catSuper || cat == catSub)
1416 limits = t.cs() == "limits" ? 1 : -1;
1418 MathAtom at = createInsetMath(t.cs(), buf);
1419 cell->push_back(at);
1423 // \notag is the same as \nonumber if amsmath is used
1424 else if ((t.cs() == "nonumber" || t.cs() == "notag") &&
1426 grid.asHullInset()->numbered(cellrow, false);
1428 else if (t.cs() == "number" && grid.asHullInset())
1429 grid.asHullInset()->numbered(cellrow, true);
1431 else if (t.cs() == "hline") {
1432 grid.rowinfo(cellrow).lines_ ++;
1435 else if (t.cs() == "sqrt") {
1437 parse(ar, FLAG_OPTION, mode);
1439 cell->push_back(MathAtom(new InsetMathRoot(buf)));
1440 cell->back().nucleus()->cell(0) = ar;
1441 parse(cell->back().nucleus()->cell(1), FLAG_ITEM, mode);
1443 cell->push_back(MathAtom(new InsetMathSqrt(buf)));
1444 parse(cell->back().nucleus()->cell(0), FLAG_ITEM, mode);
1448 else if (t.cs() == "cancelto") {
1450 parse(ar, FLAG_ITEM, mode);
1451 cell->push_back(MathAtom(new InsetMathCancelto(buf)));
1452 cell->back().nucleus()->cell(1) = ar;
1453 parse(cell->back().nucleus()->cell(0), FLAG_ITEM, mode);
1456 else if (t.cs() == "unit") {
1457 // Allowed formats \unit[val]{unit}
1459 parse(ar, FLAG_OPTION, mode);
1461 cell->push_back(MathAtom(new InsetMathFrac(buf, InsetMathFrac::UNIT)));
1462 cell->back().nucleus()->cell(0) = ar;
1463 parse(cell->back().nucleus()->cell(1), FLAG_ITEM, mode);
1465 cell->push_back(MathAtom(new InsetMathFrac(buf, InsetMathFrac::UNIT, 1)));
1466 parse(cell->back().nucleus()->cell(0), FLAG_ITEM, mode);
1470 else if (t.cs() == "unitfrac") {
1471 // Here allowed formats are \unitfrac[val]{num}{denom}
1473 parse(ar, FLAG_OPTION, mode);
1475 cell->push_back(MathAtom(new InsetMathFrac(buf, InsetMathFrac::UNITFRAC, 3)));
1476 cell->back().nucleus()->cell(2) = ar;
1478 cell->push_back(MathAtom(new InsetMathFrac(buf, InsetMathFrac::UNITFRAC)));
1480 parse(cell->back().nucleus()->cell(0), FLAG_ITEM, mode);
1481 parse(cell->back().nucleus()->cell(1), FLAG_ITEM, mode);
1484 else if (t.cs() == "cfrac") {
1485 // allowed formats are \cfrac[pos]{num}{denom}
1486 docstring const arg = getArg('[', ']');
1487 //lyxerr << "got so far: '" << arg << "'" << endl;
1489 cell->push_back(MathAtom(new InsetMathFrac(buf, InsetMathFrac::CFRACLEFT)));
1490 else if (arg == "r")
1491 cell->push_back(MathAtom(new InsetMathFrac(buf, InsetMathFrac::CFRACRIGHT)));
1492 else if (arg.empty() || arg == "c")
1493 cell->push_back(MathAtom(new InsetMathFrac(buf, InsetMathFrac::CFRAC)));
1495 error("found invalid optional argument");
1498 parse(cell->back().nucleus()->cell(0), FLAG_ITEM, mode);
1499 parse(cell->back().nucleus()->cell(1), FLAG_ITEM, mode);
1502 else if (t.cs() == "sideset") {
1503 // Here allowed formats are \sideset{_{bl}^{tl}}{_{br}^{tr}}{operator}
1505 InsetMathScript * script[2] = {0, 0};
1506 for (int i = 0; i < 2; ++i) {
1507 parse(ar[i], FLAG_ITEM, mode);
1508 if (ar[i].size() == 1)
1509 script[i] = ar[i][0].nucleus()->asScriptInset();
1511 bool const hasscript[2] = {script[0] ? true : false, script[1] ? true : false};
1512 cell->push_back(MathAtom(new InsetMathSideset(buf, hasscript[0], hasscript[1])));
1514 if (script[0]->hasDown())
1515 cell->back().nucleus()->cell(1) = script[0]->down();
1516 if (script[0]->hasUp())
1517 cell->back().nucleus()->cell(2) = script[0]->up();
1519 cell->back().nucleus()->cell(1) = ar[0];
1521 if (script[1]->hasDown())
1522 cell->back().nucleus()->cell(2 + hasscript[0]) = script[1]->down();
1523 if (script[1]->hasUp())
1524 cell->back().nucleus()->cell(3 + hasscript[0]) = script[1]->up();
1526 cell->back().nucleus()->cell(2 + hasscript[0]) = ar[1];
1527 parse(cell->back().nucleus()->cell(0), FLAG_ITEM, mode);
1530 else if (t.cs() == "stackrel") {
1531 // Here allowed formats are \stackrel[subscript]{superscript}{operator}
1533 parse(ar, FLAG_OPTION, mode);
1534 cell->push_back(MathAtom(new InsetMathStackrel(buf, !ar.empty())));
1536 cell->back().nucleus()->cell(2) = ar;
1537 parse(cell->back().nucleus()->cell(0), FLAG_ITEM, mode);
1538 parse(cell->back().nucleus()->cell(1), FLAG_ITEM, mode);
1541 else if (t.cs() == "xrightarrow" || t.cs() == "xleftarrow") {
1542 cell->push_back(createInsetMath(t.cs(), buf));
1543 parse(cell->back().nucleus()->cell(1), FLAG_OPTION, mode);
1544 parse(cell->back().nucleus()->cell(0), FLAG_ITEM, mode);
1547 else if (t.cs() == "xhookrightarrow" || t.cs() == "xhookleftarrow" ||
1548 t.cs() == "xRightarrow" || t.cs() == "xLeftarrow" ||
1549 t.cs() == "xleftrightarrow" || t.cs() == "xLeftrightarrow" ||
1550 t.cs() == "xrightharpoondown" || t.cs() == "xrightharpoonup" ||
1551 t.cs() == "xleftharpoondown" || t.cs() == "xleftharpoonup" ||
1552 t.cs() == "xleftrightharpoons" || t.cs() == "xrightleftharpoons" ||
1553 t.cs() == "xmapsto") {
1554 cell->push_back(createInsetMath(t.cs(), buf));
1555 parse(cell->back().nucleus()->cell(1), FLAG_OPTION, mode);
1556 parse(cell->back().nucleus()->cell(0), FLAG_ITEM, mode);
1559 else if (t.cs() == "ref" || t.cs() == "eqref" || t.cs() == "prettyref"
1560 || t.cs() == "pageref" || t.cs() == "vpageref" || t.cs() == "vref") {
1561 cell->push_back(MathAtom(new InsetMathRef(buf, t.cs())));
1562 docstring const opt = parse_verbatim_option();
1563 docstring const ref = parse_verbatim_item();
1565 cell->back().nucleus()->cell(1).push_back(
1566 MathAtom(new InsetMathString(opt)));
1568 cell->back().nucleus()->cell(0).push_back(
1569 MathAtom(new InsetMathString(ref)));
1572 else if (t.cs() == "left") {
1574 Token const & tl = getToken();
1575 // \| and \Vert are equivalent, and InsetMathDelim
1577 // FIXME: fix this in InsetMathDelim itself!
1578 docstring const l = tl.cs() == "|" ? from_ascii("Vert") : tl.asString();
1580 parse(ar, FLAG_RIGHT, mode);
1584 Token const & tr = getToken();
1585 docstring const r = tr.cs() == "|" ? from_ascii("Vert") : tr.asString();
1586 cell->push_back(MathAtom(new InsetMathDelim(buf, l, r, ar)));
1589 else if (t.cs() == "right") {
1590 if (flags & FLAG_RIGHT)
1592 //lyxerr << "got so far: '" << cell << "'" << endl;
1593 error("Unmatched right delimiter");
1597 else if (t.cs() == "begin") {
1598 docstring const name = getArg('{', '}');
1602 error("found invalid environment");
1606 environments_.push_back(name);
1608 if (name == "array" || name == "subarray") {
1609 docstring const valign = parse_verbatim_option() + 'c';
1610 docstring const halign = parse_verbatim_item();
1611 cell->push_back(MathAtom(new InsetMathArray(buf, name,
1612 InsetMathGrid::guessColumns(halign), 1, (char)valign[0], halign)));
1613 parse2(cell->back(), FLAG_END, mode, false);
1616 else if (name == "tabular") {
1617 docstring const valign = parse_verbatim_option() + 'c';
1618 docstring const halign = parse_verbatim_item();
1619 cell->push_back(MathAtom(new InsetMathTabular(buf, name,
1620 InsetMathGrid::guessColumns(halign), 1, (char)valign[0], halign)));
1621 parse2(cell->back(), FLAG_END, InsetMath::TEXT_MODE, false);
1624 else if (name == "split" || name == "cases") {
1625 cell->push_back(createInsetMath(name, buf));
1626 parse2(cell->back(), FLAG_END, mode, false);
1629 else if (name == "alignedat") {
1630 docstring const valign = parse_verbatim_option() + 'c';
1631 // ignore this for a while
1633 cell->push_back(MathAtom(new InsetMathSplit(buf, name, (char)valign[0])));
1634 parse2(cell->back(), FLAG_END, mode, false);
1637 else if (name == "math") {
1638 if (mode == InsetMath::UNDECIDED_MODE) {
1639 cell->push_back(MathAtom(new InsetMathHull(buf, hullSimple)));
1640 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, false);
1642 // Don't create nested math hulls (bug #5392)
1643 cell->push_back(MathAtom(new InsetMathEnsureMath(buf)));
1644 parse(cell->back().nucleus()->cell(0), FLAG_END, InsetMath::MATH_MODE);
1648 else if (name == "equation" || name == "equation*"
1649 || name == "displaymath") {
1650 if (mode != InsetMath::UNDECIDED_MODE) {
1651 error("bad math environment " + name);
1654 cell->push_back(MathAtom(new InsetMathHull(buf, hullEquation)));
1655 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, (name == "equation"));
1658 else if (name == "eqnarray" || name == "eqnarray*") {
1659 if (mode != InsetMath::UNDECIDED_MODE) {
1660 error("bad math environment " + name);
1663 cell->push_back(MathAtom(new InsetMathHull(buf, hullEqnArray)));
1664 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, !stared(name));
1667 else if (name == "align" || name == "align*") {
1668 if (mode == InsetMath::UNDECIDED_MODE) {
1669 cell->push_back(MathAtom(new InsetMathHull(buf, hullAlign)));
1670 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, !stared(name));
1672 cell->push_back(MathAtom(new InsetMathSplit(buf, name,
1673 'c', !stared(name))));
1674 parse2(cell->back(), FLAG_END, mode, !stared(name));
1678 else if (name == "flalign" || name == "flalign*") {
1679 if (mode != InsetMath::UNDECIDED_MODE) {
1680 error("bad math environment " + name);
1683 cell->push_back(MathAtom(new InsetMathHull(buf, hullFlAlign)));
1684 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, !stared(name));
1687 else if (name == "alignat" || name == "alignat*") {
1688 if (mode != InsetMath::UNDECIDED_MODE) {
1689 error("bad math environment " + name);
1692 // ignore this for a while
1694 cell->push_back(MathAtom(new InsetMathHull(buf, hullAlignAt)));
1695 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, !stared(name));
1698 else if (name == "xalignat" || name == "xalignat*") {
1699 if (mode != InsetMath::UNDECIDED_MODE) {
1700 error("bad math environment " + name);
1703 // ignore this for a while
1705 cell->push_back(MathAtom(new InsetMathHull(buf, hullXAlignAt)));
1706 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, !stared(name));
1709 else if (name == "xxalignat") {
1710 if (mode != InsetMath::UNDECIDED_MODE) {
1711 error("bad math environment " + name);
1714 // ignore this for a while
1716 cell->push_back(MathAtom(new InsetMathHull(buf, hullXXAlignAt)));
1717 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, !stared(name));
1720 else if (name == "multline" || name == "multline*") {
1721 if (mode != InsetMath::UNDECIDED_MODE) {
1722 error("bad math environment " + name);
1725 cell->push_back(MathAtom(new InsetMathHull(buf, hullMultline)));
1726 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, !stared(name));
1729 else if (name == "gather" || name == "gather*") {
1730 if (mode != InsetMath::UNDECIDED_MODE) {
1731 error("bad math environment " + name);
1734 cell->push_back(MathAtom(new InsetMathHull(buf, hullGather)));
1735 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, !stared(name));
1738 else if (latexkeys const * l = in_word_set(name)) {
1739 if (l->inset == "matrix") {
1740 cell->push_back(createInsetMath(name, buf));
1741 parse2(cell->back(), FLAG_END, mode, false);
1742 } else if (l->inset == "split") {
1743 docstring const valign = parse_verbatim_option() + 'c';
1744 cell->push_back(MathAtom(
1745 new InsetMathSplit(buf, name, (char)valign[0])));
1746 parse2(cell->back(), FLAG_END, mode, false);
1749 if (!(mode_ & Parse::QUIET)) {
1751 lyxerr << "found math environment `"
1753 << "' in symbols file with unsupported inset `"
1754 << to_utf8(l->inset)
1757 // create generic environment inset
1758 cell->push_back(MathAtom(new InsetMathEnv(buf, name)));
1759 parse(cell->back().nucleus()->cell(0), FLAG_END, mode);
1765 if (!(mode_ & Parse::QUIET)) {
1767 lyxerr << "found unknown math environment '"
1768 << to_utf8(name) << "'" << endl;
1770 // create generic environment inset
1771 cell->push_back(MathAtom(new InsetMathEnv(buf, name)));
1772 parse(cell->back().nucleus()->cell(0), FLAG_END, mode);
1776 else if (t.cs() == "kern") {
1781 Token const & t = getToken();
1785 while (num_tokens--)
1790 if (isValidLength(to_utf8(s)))
1794 cell->push_back(MathAtom(new InsetMathKern));
1796 cell->push_back(MathAtom(new InsetMathKern(s)));
1799 else if (t.cs() == "label") {
1800 // FIXME: This is swallowed in inline formulas
1801 docstring label = parse_verbatim_item();
1804 if (grid.asHullInset()) {
1805 grid.asHullInset()->label(cellrow, label);
1807 cell->push_back(createInsetMath(t.cs(), buf));
1808 cell->push_back(MathAtom(new InsetMathBrace(ar)));
1812 else if (t.cs() == "choose" || t.cs() == "over"
1813 || t.cs() == "atop" || t.cs() == "brace"
1814 || t.cs() == "brack") {
1815 MathAtom at = createInsetMath(t.cs(), buf);
1816 at.nucleus()->cell(0) = *cell;
1818 parse(at.nucleus()->cell(1), flags, mode);
1819 cell->push_back(at);
1823 else if (t.cs() == "color") {
1824 docstring const color = parse_verbatim_item();
1825 cell->push_back(MathAtom(new InsetMathColor(buf, true, color)));
1826 parse(cell->back().nucleus()->cell(0), flags, mode);
1830 else if (t.cs() == "textcolor") {
1831 docstring const color = parse_verbatim_item();
1832 cell->push_back(MathAtom(new InsetMathColor(buf, false, color)));
1833 parse(cell->back().nucleus()->cell(0), FLAG_ITEM, InsetMath::TEXT_MODE);
1836 else if (t.cs() == "normalcolor") {
1837 cell->push_back(createInsetMath(t.cs(), buf));
1838 parse(cell->back().nucleus()->cell(0), flags, mode);
1842 else if (t.cs() == "substack") {
1843 cell->push_back(createInsetMath(t.cs(), buf));
1844 parse2(cell->back(), FLAG_ITEM, mode, false);
1845 // Delete empty last row if present
1846 InsetMathGrid & subgrid =
1847 *(cell->back().nucleus()->asGridInset());
1848 if (subgrid.nrows() > 1)
1849 delEmptyLastRow(subgrid);
1852 else if (t.cs() == "xymatrix") {
1853 odocstringstream os;
1854 while (good() && nextToken().cat() != catBegin)
1855 os << getToken().asInput();
1856 cell->push_back(createInsetMath(t.cs() + os.str(), buf));
1857 parse2(cell->back(), FLAG_ITEM, mode, false);
1858 // Delete empty last row if present
1859 InsetMathGrid & subgrid =
1860 *(cell->back().nucleus()->asGridInset());
1861 if (subgrid.nrows() > 1)
1862 delEmptyLastRow(subgrid);
1865 else if (t.cs() == "Diagram") {
1866 odocstringstream os;
1867 while (good() && nextToken().cat() != catBegin)
1868 os << getToken().asInput();
1869 cell->push_back(createInsetMath(t.cs() + os.str(), buf));
1870 parse2(cell->back(), FLAG_ITEM, mode, false);
1873 else if (t.cs() == "framebox" || t.cs() == "makebox") {
1874 cell->push_back(createInsetMath(t.cs(), buf));
1875 parse(cell->back().nucleus()->cell(0), FLAG_OPTION, InsetMath::TEXT_MODE);
1876 parse(cell->back().nucleus()->cell(1), FLAG_OPTION, InsetMath::TEXT_MODE);
1877 parse(cell->back().nucleus()->cell(2), FLAG_ITEM, InsetMath::TEXT_MODE);
1880 else if (t.cs() == "tag") {
1881 if (nextToken().character() == '*') {
1883 cell->push_back(createInsetMath(t.cs() + '*', buf));
1885 cell->push_back(createInsetMath(t.cs(), buf));
1886 parse(cell->back().nucleus()->cell(0), FLAG_ITEM, InsetMath::TEXT_MODE);
1889 else if (t.cs() == "hspace") {
1890 bool const prot = nextToken().character() == '*';
1893 docstring const name = t.cs();
1894 docstring const arg = parse_verbatim_item();
1896 if (prot && arg == "\\fill")
1897 cell->push_back(MathAtom(new InsetMathSpace("hspace*{\\fill}", "")));
1898 else if (isValidLength(to_utf8(arg), &length))
1899 cell->push_back(MathAtom(new InsetMathSpace(length, prot)));
1901 // Since the Length class cannot use length variables
1902 // we must not create an InsetMathSpace.
1903 cell->push_back(MathAtom(new MathMacro(buf, name)));
1905 mathed_parse_cell(ar, '{' + arg + '}', mode_);
1910 else if (t.cs() == "smash") {
1912 if (nextToken().asInput() == "[") {
1913 // Since the phantom inset cannot handle optional arguments
1914 // other than b and t, we must not create an InsetMathPhantom
1915 // if opt is different from b and t (bug 8967).
1916 docstring const opt = parse_verbatim_option();
1917 if (opt == "t" || opt == "b") {
1918 cell->push_back(createInsetMath(t.cs() + opt, buf));
1919 parse(cell->back().nucleus()->cell(0), FLAG_ITEM, mode);
1921 docstring const arg = parse_verbatim_item();
1922 cell->push_back(MathAtom(new MathMacro(buf, t.cs())));
1924 mathed_parse_cell(ar, '[' + opt + ']', mode_);
1927 mathed_parse_cell(ar, '{' + arg + '}', mode_);
1932 cell->push_back(createInsetMath(t.cs(), buf));
1933 parse(cell->back().nucleus()->cell(0), FLAG_ITEM, mode);
1938 else if (t.cs() == "infer") {
1940 parse(ar, FLAG_OPTION, mode);
1941 cell->push_back(createInsetMath(t.cs(), buf));
1942 parse2(cell->back(), FLAG_ITEM, mode, false);
1946 else if (1 && t.cs() == "ar") {
1947 auto_ptr<InsetMathXYArrow> p(new InsetMathXYArrow);
1948 // try to read target
1949 parse(p->cell(0), FLAG_OTPTION, mode);
1950 // try to read label
1951 if (nextToken().cat() == catSuper || nextToken().cat() == catSub) {
1952 p->up_ = nextToken().cat() == catSuper;
1954 parse(p->cell(1), FLAG_ITEM, mode);
1955 //lyxerr << "read label: " << p->cell(1) << endl;
1958 cell->push_back(MathAtom(p.release()));
1959 //lyxerr << "read cell: " << cell << endl;
1963 else if (t.cs() == "lyxmathsym") {
1965 if (getToken().cat() != catBegin) {
1966 error("'{' expected in \\" + t.cs());
1971 CatCode cat = nextToken().cat();
1972 while (good() && (count || cat != catEnd)) {
1973 if (cat == catBegin)
1975 else if (cat == catEnd)
1977 cmd += getToken().asInput();
1978 cat = nextToken().cat();
1980 if (getToken().cat() != catEnd) {
1981 error("'}' expected in \\" + t.cs());
1987 cmd = Encodings::fromLaTeXCommand(cmd,
1988 Encodings::MATH_CMD | Encodings::TEXT_CMD,
1990 for (size_t i = 0; i < cmd.size(); ++i)
1991 cell->push_back(MathAtom(new InsetMathChar(cmd[i])));
1993 char_type c = rem[0];
1994 cell->push_back(MathAtom(new InsetMathChar(c)));
1995 cmd = rem.substr(1);
1999 } while (!cmd.empty());
2002 else if (!t.cs().empty()) {
2003 bool const no_mhchem =
2004 (t.cs() == "ce" || t.cs() == "cf")
2005 && buf && buf->params().use_package("mhchem") ==
2006 BufferParams::package_off;
2008 bool const is_user_macro = no_mhchem ||
2009 (buf && (mode_ & Parse::TRACKMACRO
2010 ? buf->usermacros.count(t.cs()) != 0
2011 : buf->getMacro(t.cs(), false) != 0));
2013 latexkeys const * l = in_word_set(t.cs());
2014 if (l && !is_user_macro) {
2015 if (l->inset == "big") {
2017 docstring const delim = getToken().asInput();
2018 if (InsetMathBig::isBigInsetDelim(delim))
2019 cell->push_back(MathAtom(
2020 new InsetMathBig(t.cs(), delim)));
2022 cell->push_back(createInsetMath(t.cs(), buf));
2027 else if (l->inset == "font") {
2028 cell->push_back(createInsetMath(t.cs(), buf));
2029 parse(cell->back().nucleus()->cell(0),
2030 FLAG_ITEM, asMode(mode, l->extra));
2033 else if (l->inset == "oldfont") {
2034 cell->push_back(createInsetMath(t.cs(), buf));
2035 parse(cell->back().nucleus()->cell(0),
2036 flags | FLAG_ALIGN, asMode(mode, l->extra));
2037 if (prevToken().cat() != catAlign &&
2038 prevToken().cs() != "\\")
2043 else if (l->inset == "style") {
2044 cell->push_back(createInsetMath(t.cs(), buf));
2045 parse(cell->back().nucleus()->cell(0),
2046 flags | FLAG_ALIGN, mode);
2047 if (prevToken().cat() != catAlign &&
2048 prevToken().cs() != "\\")
2054 MathAtom at = createInsetMath(t.cs(), buf);
2055 for (InsetMath::idx_type i = 0; i < at->nargs(); ++i)
2056 parse(at.nucleus()->cell(i),
2057 FLAG_ITEM, asMode(mode, l->extra));
2058 cell->push_back(at);
2063 bool is_unicode_symbol = false;
2064 if (mode == InsetMath::TEXT_MODE && !is_user_macro) {
2066 docstring cmd = prevToken().asInput();
2067 CatCode cat = nextToken().cat();
2068 if (cat == catBegin) {
2070 while (good() && (count || cat != catEnd)) {
2071 cat = nextToken().cat();
2072 cmd += getToken().asInput();
2074 if (cat == catBegin)
2076 else if (cat == catEnd)
2082 char_type c = Encodings::fromLaTeXCommand(cmd,
2083 Encodings::MATH_CMD | Encodings::TEXT_CMD,
2084 is_combining, termination);
2086 if (cat == catLetter)
2088 cmd += getToken().asInput();
2090 if (cat == catLetter)
2092 c = Encodings::fromLaTeXCommand(cmd,
2093 Encodings::MATH_CMD | Encodings::TEXT_CMD,
2094 is_combining, termination);
2098 if (nextToken().cat() == catBegin) {
2100 if (nextToken().cat() == catEnd) {
2106 while (nextToken().cat() == catSpace) {
2112 is_unicode_symbol = true;
2113 cell->push_back(MathAtom(new InsetMathChar(c)));
2115 while (num_tokens--)
2119 if (!is_unicode_symbol) {
2120 MathAtom at = is_user_macro ?
2121 MathAtom(new MathMacro(buf, t.cs()))
2122 : createInsetMath(t.cs(), buf);
2123 InsetMath::mode_type m = mode;
2124 //if (m == InsetMath::UNDECIDED_MODE)
2125 //lyxerr << "default creation: m1: " << m << endl;
2126 if (at->currentMode() != InsetMath::UNDECIDED_MODE)
2127 m = at->currentMode();
2128 //lyxerr << "default creation: m2: " << m << endl;
2129 InsetMath::idx_type start = 0;
2130 // this fails on \bigg[...\bigg]
2132 //parse(opt, FLAG_OPTION, InsetMath::VERBATIM_MODE);
2133 //if (!opt.empty()) {
2135 // at.nucleus()->cell(0) = opt;
2137 for (InsetMath::idx_type i = start; i < at->nargs(); ++i) {
2138 parse(at.nucleus()->cell(i), FLAG_ITEM, m);
2139 if (mode == InsetMath::MATH_MODE)
2142 cell->push_back(at);
2148 if (flags & FLAG_LEAVE) {
2149 flags &= ~FLAG_LEAVE;
2158 } // anonymous namespace
2161 bool mathed_parse_cell(MathData & ar, docstring const & str, Parse::flags f)
2163 return Parser(str, f, ar.buffer()).parse(ar, 0, f & Parse::TEXTMODE ?
2164 InsetMath::TEXT_MODE : InsetMath::MATH_MODE);
2168 bool mathed_parse_cell(MathData & ar, istream & is, Parse::flags f)
2170 return Parser(is, f, ar.buffer()).parse(ar, 0, f & Parse::TEXTMODE ?
2171 InsetMath::TEXT_MODE : InsetMath::MATH_MODE);
2175 bool mathed_parse_normal(Buffer * buf, MathAtom & t, docstring const & str,
2178 return Parser(str, f, buf).parse(t);
2182 bool mathed_parse_normal(Buffer * buf, MathAtom & t, Lexer & lex,
2185 return Parser(lex, f, buf).parse(t);
2189 bool mathed_parse_normal(InsetMathGrid & grid, docstring const & str,
2192 return Parser(str, f, &grid.buffer()).parse1(grid, 0, f & Parse::TEXTMODE ?
2193 InsetMath::TEXT_MODE : InsetMath::MATH_MODE, false);
2199 fill(theCatcode, theCatcode + 128, catOther);
2200 fill(theCatcode + 'a', theCatcode + 'z' + 1, catLetter);
2201 fill(theCatcode + 'A', theCatcode + 'Z' + 1, catLetter);
2203 theCatcode[int('\\')] = catEscape;
2204 theCatcode[int('{')] = catBegin;
2205 theCatcode[int('}')] = catEnd;
2206 theCatcode[int('$')] = catMath;
2207 theCatcode[int('&')] = catAlign;
2208 theCatcode[int('\n')] = catNewline;
2209 theCatcode[int('#')] = catParameter;
2210 theCatcode[int('^')] = catSuper;
2211 theCatcode[int('_')] = catSub;
2212 theCatcode[int(0x7f)] = catIgnore;
2213 theCatcode[int(' ')] = catSpace;
2214 theCatcode[int('\t')] = catSpace;
2215 theCatcode[int('\r')] = catNewline;
2216 theCatcode[int('~')] = catActive;
2217 theCatcode[int('%')] = catComment;