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)
1337 bool starred = false;
1339 if (nextToken().asInput() == "*") {
1342 } else if (nextToken().asInput() == "[")
1343 arg = getArg('[', ']');
1345 error("missing token after \\\\");
1346 // skip "{}" added in front of "[" (the
1347 // counterpart is in InsetMathGrid::eolString())
1348 // skip spaces because formula could come from tex2lyx
1349 bool skipBraces = false;
1351 if (nextToken().cat() == catBegin) {
1353 if (nextToken().cat() == catEnd) {
1357 if (nextToken().asInput() == "[")
1366 bool const added = addRow(grid, cellrow, arg, !starred);
1369 if (grid.asHullInset())
1370 grid.asHullInset()->numbered(
1372 cell = &grid.cell(grid.index(cellrow,
1378 else if (t.cs() == "multicolumn") {
1379 // extract column count and insert dummy cells
1381 parse(count, FLAG_ITEM, mode);
1383 if (!extractNumber(count, cols)) {
1385 lyxerr << " can't extract number of cells from " << count << endl;
1387 // resize the table if necessary
1388 for (int i = 0; i < cols; ++i) {
1389 if (addCol(grid, cellcol)) {
1390 cell = &grid.cell(grid.index(
1392 // mark this as dummy
1393 grid.cellinfo(grid.index(
1394 cellrow, cellcol)).dummy_ = true;
1397 // the last cell is the real thing, not a dummy
1398 grid.cellinfo(grid.index(cellrow, cellcol)).dummy_ = false;
1400 // read special alignment
1402 parse(align, FLAG_ITEM, mode);
1403 //grid.cellinfo(grid.index(cellrow, cellcol)).align_ = extractString(align);
1405 // parse the remaining contents into the "real" cell
1406 parse(*cell, FLAG_ITEM, mode);
1410 else if (t.cs() == "limits" || t.cs() == "nolimits") {
1411 CatCode const cat = nextToken().cat();
1412 if (cat == catSuper || cat == catSub)
1413 limits = t.cs() == "limits" ? 1 : -1;
1415 MathAtom at = createInsetMath(t.cs(), buf);
1416 cell->push_back(at);
1420 // \notag is the same as \nonumber if amsmath is used
1421 else if ((t.cs() == "nonumber" || t.cs() == "notag") &&
1423 grid.asHullInset()->numbered(cellrow, false);
1425 else if (t.cs() == "number" && grid.asHullInset())
1426 grid.asHullInset()->numbered(cellrow, true);
1428 else if (t.cs() == "hline") {
1429 grid.rowinfo(cellrow).lines_ ++;
1432 else if (t.cs() == "sqrt") {
1434 parse(ar, FLAG_OPTION, mode);
1436 cell->push_back(MathAtom(new InsetMathRoot(buf)));
1437 cell->back().nucleus()->cell(0) = ar;
1438 parse(cell->back().nucleus()->cell(1), FLAG_ITEM, mode);
1440 cell->push_back(MathAtom(new InsetMathSqrt(buf)));
1441 parse(cell->back().nucleus()->cell(0), FLAG_ITEM, mode);
1445 else if (t.cs() == "cancelto") {
1447 parse(ar, FLAG_ITEM, mode);
1448 cell->push_back(MathAtom(new InsetMathCancelto(buf)));
1449 cell->back().nucleus()->cell(1) = ar;
1450 parse(cell->back().nucleus()->cell(0), FLAG_ITEM, mode);
1453 else if (t.cs() == "unit") {
1454 // Allowed formats \unit[val]{unit}
1456 parse(ar, FLAG_OPTION, mode);
1458 cell->push_back(MathAtom(new InsetMathFrac(buf, InsetMathFrac::UNIT)));
1459 cell->back().nucleus()->cell(0) = ar;
1460 parse(cell->back().nucleus()->cell(1), FLAG_ITEM, mode);
1462 cell->push_back(MathAtom(new InsetMathFrac(buf, InsetMathFrac::UNIT, 1)));
1463 parse(cell->back().nucleus()->cell(0), FLAG_ITEM, mode);
1467 else if (t.cs() == "unitfrac") {
1468 // Here allowed formats are \unitfrac[val]{num}{denom}
1470 parse(ar, FLAG_OPTION, mode);
1472 cell->push_back(MathAtom(new InsetMathFrac(buf, InsetMathFrac::UNITFRAC, 3)));
1473 cell->back().nucleus()->cell(2) = ar;
1475 cell->push_back(MathAtom(new InsetMathFrac(buf, InsetMathFrac::UNITFRAC)));
1477 parse(cell->back().nucleus()->cell(0), FLAG_ITEM, mode);
1478 parse(cell->back().nucleus()->cell(1), FLAG_ITEM, mode);
1481 else if (t.cs() == "cfrac") {
1482 // allowed formats are \cfrac[pos]{num}{denom}
1483 docstring const arg = getArg('[', ']');
1484 //lyxerr << "got so far: '" << arg << "'" << endl;
1486 cell->push_back(MathAtom(new InsetMathFrac(buf, InsetMathFrac::CFRACLEFT)));
1487 else if (arg == "r")
1488 cell->push_back(MathAtom(new InsetMathFrac(buf, InsetMathFrac::CFRACRIGHT)));
1489 else if (arg.empty() || arg == "c")
1490 cell->push_back(MathAtom(new InsetMathFrac(buf, InsetMathFrac::CFRAC)));
1492 error("found invalid optional argument");
1495 parse(cell->back().nucleus()->cell(0), FLAG_ITEM, mode);
1496 parse(cell->back().nucleus()->cell(1), FLAG_ITEM, mode);
1499 else if (t.cs() == "sideset") {
1500 // Here allowed formats are \sideset{_{bl}^{tl}}{_{br}^{tr}}{operator}
1502 InsetMathScript * script[2] = {0, 0};
1503 for (int i = 0; i < 2; ++i) {
1504 parse(ar[i], FLAG_ITEM, mode);
1505 if (ar[i].size() == 1)
1506 script[i] = ar[i][0].nucleus()->asScriptInset();
1508 bool const hasscript[2] = {script[0] ? true : false, script[1] ? true : false};
1509 cell->push_back(MathAtom(new InsetMathSideset(buf, hasscript[0], hasscript[1])));
1511 if (script[0]->hasDown())
1512 cell->back().nucleus()->cell(1) = script[0]->down();
1513 if (script[0]->hasUp())
1514 cell->back().nucleus()->cell(2) = script[0]->up();
1516 cell->back().nucleus()->cell(1) = ar[0];
1518 if (script[1]->hasDown())
1519 cell->back().nucleus()->cell(2 + hasscript[0]) = script[1]->down();
1520 if (script[1]->hasUp())
1521 cell->back().nucleus()->cell(3 + hasscript[0]) = script[1]->up();
1523 cell->back().nucleus()->cell(2 + hasscript[0]) = ar[1];
1524 parse(cell->back().nucleus()->cell(0), FLAG_ITEM, mode);
1527 else if (t.cs() == "stackrel") {
1528 // Here allowed formats are \stackrel[subscript]{superscript}{operator}
1530 parse(ar, FLAG_OPTION, mode);
1531 cell->push_back(MathAtom(new InsetMathStackrel(buf, !ar.empty())));
1533 cell->back().nucleus()->cell(2) = ar;
1534 parse(cell->back().nucleus()->cell(0), FLAG_ITEM, mode);
1535 parse(cell->back().nucleus()->cell(1), FLAG_ITEM, mode);
1538 else if (t.cs() == "xrightarrow" || t.cs() == "xleftarrow") {
1539 cell->push_back(createInsetMath(t.cs(), buf));
1540 parse(cell->back().nucleus()->cell(1), FLAG_OPTION, mode);
1541 parse(cell->back().nucleus()->cell(0), FLAG_ITEM, mode);
1544 else if (t.cs() == "xhookrightarrow" || t.cs() == "xhookleftarrow" ||
1545 t.cs() == "xRightarrow" || t.cs() == "xLeftarrow" ||
1546 t.cs() == "xleftrightarrow" || t.cs() == "xLeftrightarrow" ||
1547 t.cs() == "xrightharpoondown" || t.cs() == "xrightharpoonup" ||
1548 t.cs() == "xleftharpoondown" || t.cs() == "xleftharpoonup" ||
1549 t.cs() == "xleftrightharpoons" || t.cs() == "xrightleftharpoons" ||
1550 t.cs() == "xmapsto") {
1551 cell->push_back(createInsetMath(t.cs(), buf));
1552 parse(cell->back().nucleus()->cell(1), FLAG_OPTION, mode);
1553 parse(cell->back().nucleus()->cell(0), FLAG_ITEM, mode);
1556 else if (t.cs() == "ref" || t.cs() == "eqref" || t.cs() == "prettyref"
1557 || t.cs() == "pageref" || t.cs() == "vpageref" || t.cs() == "vref") {
1558 cell->push_back(MathAtom(new InsetMathRef(buf, t.cs())));
1559 docstring const opt = parse_verbatim_option();
1560 docstring const ref = parse_verbatim_item();
1562 cell->back().nucleus()->cell(1).push_back(
1563 MathAtom(new InsetMathString(opt)));
1565 cell->back().nucleus()->cell(0).push_back(
1566 MathAtom(new InsetMathString(ref)));
1569 else if (t.cs() == "left") {
1571 Token const & tl = getToken();
1572 // \| and \Vert are equivalent, and InsetMathDelim
1574 // FIXME: fix this in InsetMathDelim itself!
1575 docstring const l = tl.cs() == "|" ? from_ascii("Vert") : tl.asString();
1577 parse(ar, FLAG_RIGHT, mode);
1581 Token const & tr = getToken();
1582 docstring const r = tr.cs() == "|" ? from_ascii("Vert") : tr.asString();
1583 cell->push_back(MathAtom(new InsetMathDelim(buf, l, r, ar)));
1586 else if (t.cs() == "right") {
1587 if (flags & FLAG_RIGHT)
1589 //lyxerr << "got so far: '" << cell << "'" << endl;
1590 error("Unmatched right delimiter");
1594 else if (t.cs() == "begin") {
1595 docstring const name = getArg('{', '}');
1599 error("found invalid environment");
1603 environments_.push_back(name);
1605 if (name == "array" || name == "subarray") {
1606 docstring const valign = parse_verbatim_option() + 'c';
1607 docstring const halign = parse_verbatim_item();
1608 cell->push_back(MathAtom(new InsetMathArray(buf, name,
1609 InsetMathGrid::guessColumns(halign), 1, (char)valign[0], halign)));
1610 parse2(cell->back(), FLAG_END, mode, false);
1613 else if (name == "tabular") {
1614 docstring const valign = parse_verbatim_option() + 'c';
1615 docstring const halign = parse_verbatim_item();
1616 cell->push_back(MathAtom(new InsetMathTabular(buf, name,
1617 InsetMathGrid::guessColumns(halign), 1, (char)valign[0], halign)));
1618 parse2(cell->back(), FLAG_END, InsetMath::TEXT_MODE, false);
1621 else if (name == "split" || name == "cases") {
1622 cell->push_back(createInsetMath(name, buf));
1623 parse2(cell->back(), FLAG_END, mode, false);
1626 else if (name == "alignedat") {
1627 docstring const valign = parse_verbatim_option() + 'c';
1628 // ignore this for a while
1630 cell->push_back(MathAtom(new InsetMathSplit(buf, name, (char)valign[0])));
1631 parse2(cell->back(), FLAG_END, mode, false);
1634 else if (name == "math") {
1635 if (mode == InsetMath::UNDECIDED_MODE) {
1636 cell->push_back(MathAtom(new InsetMathHull(buf, hullSimple)));
1637 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, false);
1639 // Don't create nested math hulls (bug #5392)
1640 cell->push_back(MathAtom(new InsetMathEnsureMath(buf)));
1641 parse(cell->back().nucleus()->cell(0), FLAG_END, InsetMath::MATH_MODE);
1645 else if (name == "equation" || name == "equation*"
1646 || name == "displaymath") {
1647 if (mode != InsetMath::UNDECIDED_MODE) {
1648 error("bad math environment " + name);
1651 cell->push_back(MathAtom(new InsetMathHull(buf, hullEquation)));
1652 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, (name == "equation"));
1655 else if (name == "eqnarray" || name == "eqnarray*") {
1656 if (mode != InsetMath::UNDECIDED_MODE) {
1657 error("bad math environment " + name);
1660 cell->push_back(MathAtom(new InsetMathHull(buf, hullEqnArray)));
1661 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, !stared(name));
1664 else if (name == "align" || name == "align*") {
1665 if (mode == InsetMath::UNDECIDED_MODE) {
1666 cell->push_back(MathAtom(new InsetMathHull(buf, hullAlign)));
1667 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, !stared(name));
1669 cell->push_back(MathAtom(new InsetMathSplit(buf, name,
1670 'c', !stared(name))));
1671 parse2(cell->back(), FLAG_END, mode, !stared(name));
1675 else if (name == "flalign" || name == "flalign*") {
1676 if (mode != InsetMath::UNDECIDED_MODE) {
1677 error("bad math environment " + name);
1680 cell->push_back(MathAtom(new InsetMathHull(buf, hullFlAlign)));
1681 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, !stared(name));
1684 else if (name == "alignat" || name == "alignat*") {
1685 if (mode != InsetMath::UNDECIDED_MODE) {
1686 error("bad math environment " + name);
1689 // ignore this for a while
1691 cell->push_back(MathAtom(new InsetMathHull(buf, hullAlignAt)));
1692 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, !stared(name));
1695 else if (name == "xalignat" || name == "xalignat*") {
1696 if (mode != InsetMath::UNDECIDED_MODE) {
1697 error("bad math environment " + name);
1700 // ignore this for a while
1702 cell->push_back(MathAtom(new InsetMathHull(buf, hullXAlignAt)));
1703 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, !stared(name));
1706 else if (name == "xxalignat") {
1707 if (mode != InsetMath::UNDECIDED_MODE) {
1708 error("bad math environment " + name);
1711 // ignore this for a while
1713 cell->push_back(MathAtom(new InsetMathHull(buf, hullXXAlignAt)));
1714 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, !stared(name));
1717 else if (name == "multline" || name == "multline*") {
1718 if (mode != InsetMath::UNDECIDED_MODE) {
1719 error("bad math environment " + name);
1722 cell->push_back(MathAtom(new InsetMathHull(buf, hullMultline)));
1723 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, !stared(name));
1726 else if (name == "gather" || name == "gather*") {
1727 if (mode != InsetMath::UNDECIDED_MODE) {
1728 error("bad math environment " + name);
1731 cell->push_back(MathAtom(new InsetMathHull(buf, hullGather)));
1732 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, !stared(name));
1735 else if (latexkeys const * l = in_word_set(name)) {
1736 if (l->inset == "matrix") {
1737 cell->push_back(createInsetMath(name, buf));
1738 parse2(cell->back(), FLAG_END, mode, false);
1739 } else if (l->inset == "split") {
1740 docstring const valign = parse_verbatim_option() + 'c';
1741 cell->push_back(MathAtom(
1742 new InsetMathSplit(buf, name, (char)valign[0])));
1743 parse2(cell->back(), FLAG_END, mode, false);
1746 if (!(mode_ & Parse::QUIET)) {
1748 lyxerr << "found math environment `"
1750 << "' in symbols file with unsupported inset `"
1754 // create generic environment inset
1755 cell->push_back(MathAtom(new InsetMathEnv(buf, name)));
1756 parse(cell->back().nucleus()->cell(0), FLAG_END, mode);
1762 if (!(mode_ & Parse::QUIET)) {
1764 lyxerr << "found unknown math environment '"
1765 << to_utf8(name) << "'" << endl;
1767 // create generic environment inset
1768 cell->push_back(MathAtom(new InsetMathEnv(buf, name)));
1769 parse(cell->back().nucleus()->cell(0), FLAG_END, mode);
1773 else if (t.cs() == "kern") {
1778 Token const & t = getToken();
1782 while (num_tokens--)
1787 if (isValidLength(to_utf8(s)))
1791 cell->push_back(MathAtom(new InsetMathKern));
1793 cell->push_back(MathAtom(new InsetMathKern(s)));
1796 else if (t.cs() == "label") {
1797 // FIXME: This is swallowed in inline formulas
1798 docstring label = parse_verbatim_item();
1801 if (grid.asHullInset()) {
1802 grid.asHullInset()->label(cellrow, label);
1804 cell->push_back(createInsetMath(t.cs(), buf));
1805 cell->push_back(MathAtom(new InsetMathBrace(ar)));
1809 else if (t.cs() == "choose" || t.cs() == "over"
1810 || t.cs() == "atop" || t.cs() == "brace"
1811 || t.cs() == "brack") {
1812 MathAtom at = createInsetMath(t.cs(), buf);
1813 at.nucleus()->cell(0) = *cell;
1815 parse(at.nucleus()->cell(1), flags, mode);
1816 cell->push_back(at);
1820 else if (t.cs() == "color") {
1821 docstring const color = parse_verbatim_item();
1822 cell->push_back(MathAtom(new InsetMathColor(buf, true, color)));
1823 parse(cell->back().nucleus()->cell(0), flags, mode);
1827 else if (t.cs() == "textcolor") {
1828 docstring const color = parse_verbatim_item();
1829 cell->push_back(MathAtom(new InsetMathColor(buf, false, color)));
1830 parse(cell->back().nucleus()->cell(0), FLAG_ITEM, InsetMath::TEXT_MODE);
1833 else if (t.cs() == "normalcolor") {
1834 cell->push_back(createInsetMath(t.cs(), buf));
1835 parse(cell->back().nucleus()->cell(0), flags, mode);
1839 else if (t.cs() == "substack") {
1840 cell->push_back(createInsetMath(t.cs(), buf));
1841 parse2(cell->back(), FLAG_ITEM, mode, false);
1842 // Delete empty last row if present
1843 InsetMathGrid & subgrid =
1844 *(cell->back().nucleus()->asGridInset());
1845 if (subgrid.nrows() > 1)
1846 delEmptyLastRow(subgrid);
1849 else if (t.cs() == "xymatrix") {
1850 odocstringstream os;
1851 while (good() && nextToken().cat() != catBegin)
1852 os << getToken().asInput();
1853 cell->push_back(createInsetMath(t.cs() + os.str(), buf));
1854 parse2(cell->back(), FLAG_ITEM, mode, false);
1855 // Delete empty last row if present
1856 InsetMathGrid & subgrid =
1857 *(cell->back().nucleus()->asGridInset());
1858 if (subgrid.nrows() > 1)
1859 delEmptyLastRow(subgrid);
1862 else if (t.cs() == "Diagram") {
1863 odocstringstream os;
1864 while (good() && nextToken().cat() != catBegin)
1865 os << getToken().asInput();
1866 cell->push_back(createInsetMath(t.cs() + os.str(), buf));
1867 parse2(cell->back(), FLAG_ITEM, mode, false);
1870 else if (t.cs() == "framebox" || t.cs() == "makebox") {
1871 cell->push_back(createInsetMath(t.cs(), buf));
1872 parse(cell->back().nucleus()->cell(0), FLAG_OPTION, InsetMath::TEXT_MODE);
1873 parse(cell->back().nucleus()->cell(1), FLAG_OPTION, InsetMath::TEXT_MODE);
1874 parse(cell->back().nucleus()->cell(2), FLAG_ITEM, InsetMath::TEXT_MODE);
1877 else if (t.cs() == "tag") {
1878 if (nextToken().character() == '*') {
1880 cell->push_back(createInsetMath(t.cs() + '*', buf));
1882 cell->push_back(createInsetMath(t.cs(), buf));
1883 parse(cell->back().nucleus()->cell(0), FLAG_ITEM, InsetMath::TEXT_MODE);
1886 else if (t.cs() == "hspace") {
1887 bool const prot = nextToken().character() == '*';
1890 docstring const name = t.cs();
1891 docstring const arg = parse_verbatim_item();
1893 if (prot && arg == "\\fill")
1894 cell->push_back(MathAtom(new InsetMathSpace("hspace*{\\fill}", "")));
1895 else if (isValidLength(to_utf8(arg), &length))
1896 cell->push_back(MathAtom(new InsetMathSpace(length, prot)));
1898 // Since the Length class cannot use length variables
1899 // we must not create an InsetMathSpace.
1900 cell->push_back(MathAtom(new MathMacro(buf, name)));
1902 mathed_parse_cell(ar, '{' + arg + '}', mode_);
1907 else if (t.cs() == "smash") {
1909 if (nextToken().asInput() == "[") {
1910 // Since the phantom inset cannot handle optional arguments
1911 // other than b and t, we must not create an InsetMathPhantom
1912 // if opt is different from b and t (bug 8967).
1913 docstring const opt = parse_verbatim_option();
1914 if (opt == "t" || opt == "b") {
1915 cell->push_back(createInsetMath(t.cs() + opt, buf));
1916 parse(cell->back().nucleus()->cell(0), FLAG_ITEM, mode);
1918 docstring const arg = parse_verbatim_item();
1919 cell->push_back(MathAtom(new MathMacro(buf, t.cs())));
1921 mathed_parse_cell(ar, '[' + opt + ']', mode_);
1924 mathed_parse_cell(ar, '{' + arg + '}', mode_);
1929 cell->push_back(createInsetMath(t.cs(), buf));
1930 parse(cell->back().nucleus()->cell(0), FLAG_ITEM, mode);
1935 else if (t.cs() == "infer") {
1937 parse(ar, FLAG_OPTION, mode);
1938 cell->push_back(createInsetMath(t.cs(), buf));
1939 parse2(cell->back(), FLAG_ITEM, mode, false);
1943 else if (1 && t.cs() == "ar") {
1944 auto_ptr<InsetMathXYArrow> p(new InsetMathXYArrow);
1945 // try to read target
1946 parse(p->cell(0), FLAG_OTPTION, mode);
1947 // try to read label
1948 if (nextToken().cat() == catSuper || nextToken().cat() == catSub) {
1949 p->up_ = nextToken().cat() == catSuper;
1951 parse(p->cell(1), FLAG_ITEM, mode);
1952 //lyxerr << "read label: " << p->cell(1) << endl;
1955 cell->push_back(MathAtom(p.release()));
1956 //lyxerr << "read cell: " << cell << endl;
1960 else if (t.cs() == "lyxmathsym") {
1962 if (getToken().cat() != catBegin) {
1963 error("'{' expected in \\" + t.cs());
1968 CatCode cat = nextToken().cat();
1969 while (good() && (count || cat != catEnd)) {
1970 if (cat == catBegin)
1972 else if (cat == catEnd)
1974 cmd += getToken().asInput();
1975 cat = nextToken().cat();
1977 if (getToken().cat() != catEnd) {
1978 error("'}' expected in \\" + t.cs());
1984 cmd = Encodings::fromLaTeXCommand(cmd,
1985 Encodings::MATH_CMD | Encodings::TEXT_CMD,
1987 for (size_t i = 0; i < cmd.size(); ++i)
1988 cell->push_back(MathAtom(new InsetMathChar(cmd[i])));
1990 char_type c = rem[0];
1991 cell->push_back(MathAtom(new InsetMathChar(c)));
1992 cmd = rem.substr(1);
1996 } while (!cmd.empty());
1999 else if (!t.cs().empty()) {
2000 bool const no_mhchem =
2001 (t.cs() == "ce" || t.cs() == "cf")
2002 && buf && buf->params().use_package("mhchem") ==
2003 BufferParams::package_off;
2005 bool const is_user_macro = no_mhchem ||
2006 (buf && (mode_ & Parse::TRACKMACRO
2007 ? buf->usermacros.count(t.cs()) != 0
2008 : buf->getMacro(t.cs(), false) != 0));
2010 latexkeys const * l = in_word_set(t.cs());
2011 if (l && !is_user_macro) {
2012 if (l->inset == "big") {
2014 docstring const delim = getToken().asInput();
2015 if (InsetMathBig::isBigInsetDelim(delim))
2016 cell->push_back(MathAtom(
2017 new InsetMathBig(t.cs(), delim)));
2019 cell->push_back(createInsetMath(t.cs(), buf));
2024 else if (l->inset == "font") {
2025 cell->push_back(createInsetMath(t.cs(), buf));
2026 parse(cell->back().nucleus()->cell(0),
2027 FLAG_ITEM, asMode(mode, l->extra));
2030 else if (l->inset == "oldfont") {
2031 cell->push_back(createInsetMath(t.cs(), buf));
2032 parse(cell->back().nucleus()->cell(0),
2033 flags | FLAG_ALIGN, asMode(mode, l->extra));
2034 if (prevToken().cat() != catAlign &&
2035 prevToken().cs() != "\\")
2040 else if (l->inset == "style") {
2041 cell->push_back(createInsetMath(t.cs(), buf));
2042 parse(cell->back().nucleus()->cell(0),
2043 flags | FLAG_ALIGN, mode);
2044 if (prevToken().cat() != catAlign &&
2045 prevToken().cs() != "\\")
2051 MathAtom at = createInsetMath(t.cs(), buf);
2052 for (InsetMath::idx_type i = 0; i < at->nargs(); ++i)
2053 parse(at.nucleus()->cell(i),
2054 FLAG_ITEM, asMode(mode, l->extra));
2055 cell->push_back(at);
2060 bool is_unicode_symbol = false;
2061 if (mode == InsetMath::TEXT_MODE && !is_user_macro) {
2063 docstring cmd = prevToken().asInput();
2064 CatCode cat = nextToken().cat();
2065 if (cat == catBegin) {
2067 while (good() && (count || cat != catEnd)) {
2068 cat = nextToken().cat();
2069 cmd += getToken().asInput();
2071 if (cat == catBegin)
2073 else if (cat == catEnd)
2079 char_type c = Encodings::fromLaTeXCommand(cmd,
2080 Encodings::MATH_CMD | Encodings::TEXT_CMD,
2081 is_combining, termination);
2083 if (cat == catLetter)
2085 cmd += getToken().asInput();
2087 if (cat == catLetter)
2089 c = Encodings::fromLaTeXCommand(cmd,
2090 Encodings::MATH_CMD | Encodings::TEXT_CMD,
2091 is_combining, termination);
2095 if (nextToken().cat() == catBegin) {
2097 if (nextToken().cat() == catEnd) {
2103 while (nextToken().cat() == catSpace) {
2109 is_unicode_symbol = true;
2110 cell->push_back(MathAtom(new InsetMathChar(c)));
2112 while (num_tokens--)
2116 if (!is_unicode_symbol) {
2117 MathAtom at = is_user_macro ?
2118 MathAtom(new MathMacro(buf, t.cs()))
2119 : createInsetMath(t.cs(), buf);
2120 InsetMath::mode_type m = mode;
2121 //if (m == InsetMath::UNDECIDED_MODE)
2122 //lyxerr << "default creation: m1: " << m << endl;
2123 if (at->currentMode() != InsetMath::UNDECIDED_MODE)
2124 m = at->currentMode();
2125 //lyxerr << "default creation: m2: " << m << endl;
2126 InsetMath::idx_type start = 0;
2127 // this fails on \bigg[...\bigg]
2129 //parse(opt, FLAG_OPTION, InsetMath::VERBATIM_MODE);
2130 //if (!opt.empty()) {
2132 // at.nucleus()->cell(0) = opt;
2134 for (InsetMath::idx_type i = start; i < at->nargs(); ++i) {
2135 parse(at.nucleus()->cell(i), FLAG_ITEM, m);
2136 if (mode == InsetMath::MATH_MODE)
2139 cell->push_back(at);
2145 if (flags & FLAG_LEAVE) {
2146 flags &= ~FLAG_LEAVE;
2155 } // anonymous namespace
2158 // FIXME This will likely need some work.
2159 char const * latexkeys::MathMLtype() const
2161 if (extra == "mathord")
2167 bool mathed_parse_cell(MathData & ar, docstring const & str, Parse::flags f)
2169 return Parser(str, f, ar.buffer()).parse(ar, 0, f & Parse::TEXTMODE ?
2170 InsetMath::TEXT_MODE : InsetMath::MATH_MODE);
2174 bool mathed_parse_cell(MathData & ar, istream & is, Parse::flags f)
2176 return Parser(is, f, ar.buffer()).parse(ar, 0, f & Parse::TEXTMODE ?
2177 InsetMath::TEXT_MODE : InsetMath::MATH_MODE);
2181 bool mathed_parse_normal(Buffer * buf, MathAtom & t, docstring const & str,
2184 return Parser(str, f, buf).parse(t);
2188 bool mathed_parse_normal(Buffer * buf, MathAtom & t, Lexer & lex,
2191 return Parser(lex, f, buf).parse(t);
2195 bool mathed_parse_normal(InsetMathGrid & grid, docstring const & str,
2198 return Parser(str, f, &grid.buffer()).parse1(grid, 0, f & Parse::TEXTMODE ?
2199 InsetMath::TEXT_MODE : InsetMath::MATH_MODE, false);
2205 fill(theCatcode, theCatcode + 128, catOther);
2206 fill(theCatcode + 'a', theCatcode + 'z' + 1, catLetter);
2207 fill(theCatcode + 'A', theCatcode + 'Z' + 1, catLetter);
2209 theCatcode[int('\\')] = catEscape;
2210 theCatcode[int('{')] = catBegin;
2211 theCatcode[int('}')] = catEnd;
2212 theCatcode[int('$')] = catMath;
2213 theCatcode[int('&')] = catAlign;
2214 theCatcode[int('\n')] = catNewline;
2215 theCatcode[int('#')] = catParameter;
2216 theCatcode[int('^')] = catSuper;
2217 theCatcode[int('_')] = catSub;
2218 theCatcode[int(0x7f)] = catIgnore;
2219 theCatcode[int(' ')] = catSpace;
2220 theCatcode[int('\t')] = catSpace;
2221 theCatcode[int('\r')] = catNewline;
2222 theCatcode[int('~')] = catActive;
2223 theCatcode[int('%')] = catComment;