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 "InsetMathMacro.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 "InsetMathMacroTemplate.h"
67 #include "MathExtern.h"
68 #include "MathFactory.h"
69 #include "InsetMathMacroArgument.h"
70 #include "MathSupport.h"
73 #include "BufferParams.h"
77 #include "support/convert.h"
78 #include "support/debug.h"
79 #include "support/docstream.h"
80 #include "support/unique_ptr.h"
92 InsetMath::mode_type asMode(InsetMath::mode_type oldmode, docstring const & str)
94 //lyxerr << "handling mode: '" << str << "'" << endl;
95 if (str == "mathmode")
96 return InsetMath::MATH_MODE;
97 if (str == "textmode" || str == "forcetext")
98 return InsetMath::TEXT_MODE;
103 bool stared(docstring const & s)
105 size_t const n = s.size();
106 return n && s[n - 1] == '*';
110 docstring const repl(docstring const & oldstr, char_type const c,
111 docstring const & macro, bool textmode = false)
117 for (i = 0, j = 0; i < oldstr.size(); ++i) {
118 if (c == oldstr[i]) {
119 newstr.append(oldstr, j, i - j);
120 newstr.append(macro);
122 if (macro.size() > 2 && j < oldstr.size())
123 newstr += (textmode && oldstr[j] == ' ' ? '\\' : ' ');
131 newstr.append(oldstr, j, i - j);
136 docstring escapeSpecialChars(docstring const & str, bool textmode)
138 docstring const backslash = textmode ? from_ascii("\\textbackslash")
139 : from_ascii("\\backslash");
140 docstring const caret = textmode ? from_ascii("\\textasciicircum")
141 : from_ascii("\\mathcircumflex");
142 docstring const tilde = textmode ? from_ascii("\\textasciitilde")
143 : from_ascii("\\sim");
145 return repl(repl(repl(repl(repl(repl(repl(repl(repl(repl(str,
146 '\\', backslash, textmode),
147 '^', caret, textmode),
148 '~', tilde, textmode),
149 '_', from_ascii("\\_")),
150 '$', from_ascii("\\$")),
151 '#', from_ascii("\\#")),
152 '&', from_ascii("\\&")),
153 '%', from_ascii("\\%")),
154 '{', from_ascii("\\{")),
155 '}', from_ascii("\\}"));
160 * Add the row \p cellrow to \p grid.
161 * \returns whether the row could be added. Adding a row can fail for
162 * environments like "equation" that have a fixed number of rows.
164 bool addRow(InsetMathGrid & grid, InsetMathGrid::row_type & cellrow,
165 docstring const & vskip, bool allow_newpage = true)
168 if (cellrow == grid.nrows()) {
169 //lyxerr << "adding row " << cellrow << endl;
170 grid.addRow(cellrow - 1);
171 if (cellrow == grid.nrows()) {
172 // We can't add a row to this grid, so let's
173 // append the content of this cell to the previous
175 // This does not happen in well formed .lyx files,
176 // but LyX versions 1.3.x and older could create
177 // such files and tex2lyx can still do that.
179 lyxerr << "ignoring extra row";
181 lyxerr << " with extra space " << to_utf8(vskip);
183 lyxerr << " with no page break allowed";
184 lyxerr << '.' << endl;
188 grid.vcrskip(Length(to_utf8(vskip)), cellrow - 1);
189 grid.rowinfo(cellrow - 1).allow_newpage = allow_newpage;
195 * Add the column \p cellcol to \p grid.
196 * \returns whether the column could be added. Adding a column can fail for
197 * environments like "eqnarray" that have a fixed number of columns.
199 bool addCol(InsetMathGrid & grid, InsetMathGrid::col_type & cellcol)
202 if (cellcol == grid.ncols()) {
203 //lyxerr << "adding column " << cellcol << endl;
204 grid.addCol(cellcol);
205 if (cellcol == grid.ncols()) {
206 // We can't add a column to this grid, so let's
207 // append the content of this cell to the previous
209 // This does not happen in well formed .lyx files,
210 // but LyX versions 1.3.x and older could create
211 // such files and tex2lyx can still do that.
213 lyxerr << "ignoring extra column." << endl;
222 * Check whether the last row is empty and remove it if yes.
223 * Otherwise the following code
231 * will result in a grid with 3 rows (+ the dummy row that is always present),
232 * because the last '\\' opens a new row.
233 * Do never delete a row that contains a multicolumn, even if all cells empty,
234 * since the multicolumn information would get lost otherwise.
235 * Note that this is only needed for inner-hull grid types, such as array
236 * or aligned, but not for outer-hull grid types, such as eqnarray or align.
238 void delEmptyLastRow(InsetMathGrid & grid)
240 InsetMathGrid::row_type const row = grid.nrows() - 1;
241 for (InsetMathGrid::col_type col = 0; col < grid.ncols(); ++col) {
242 InsetMathGrid::idx_type const idx = grid.index(row, col);
243 if (!grid.cell(idx).empty() ||
244 grid.cellinfo(idx).multi != InsetMathGrid::CELL_NORMAL)
247 // Copy the row information of the empty row (which would contain the
248 // last hline in the example above) to the dummy row and delete the
250 grid.rowinfo(row + 1) = grid.rowinfo(row);
256 * Tell whether the environment name corresponds to an inner-hull grid type.
258 bool innerHull(docstring const & name)
260 // For [bB]matrix, [vV]matrix, and pmatrix we can check the suffix only
261 return name == "array" || name == "cases" || name == "aligned"
262 || name == "alignedat" || name == "gathered" || name == "split"
263 || name == "subarray" || name == "tabular" || name == "matrix"
264 || name == "smallmatrix" || name.substr(1) == "matrix";
268 // These are TeX's catcodes
270 catEscape, // 0 backslash
280 catSpace, // 10 space
281 catLetter, // 11 a-zA-Z
282 catOther, // 12 none of the above
285 catInvalid // 15 <delete>
288 CatCode theCatcode[128];
291 inline CatCode catcode(char_type c)
293 /* The only characters that are not catOther lie in the pure ASCII
294 * range. Therefore theCatcode has only 128 entries.
295 * TeX itself deals with 8bit characters, so if needed this table
296 * could be enlarged to 256 entries.
297 * Any larger value does not make sense, since the fact that we use
298 * unicode internally does not change Knuth's TeX engine.
299 * Apart from that a table for the full 21bit UCS4 range would waste
300 * too much memory. */
304 return theCatcode[c];
309 FLAG_ALIGN = 1 << 0, // next & or \\ ends the parsing process
310 FLAG_BRACE_LAST = 1 << 1, // next closing brace ends the parsing
311 FLAG_RIGHT = 1 << 2, // next \\right ends the parsing process
312 FLAG_END = 1 << 3, // next \\end ends the parsing process
313 FLAG_BRACK_LAST = 1 << 4, // next closing bracket ends the parsing
314 FLAG_TEXTMODE = 1 << 5, // we are in a box
315 FLAG_ITEM = 1 << 6, // read a (possibly braced) token
316 FLAG_LEAVE = 1 << 7, // leave the loop at the end
317 FLAG_SIMPLE = 1 << 8, // next $ leaves the loop
318 FLAG_EQUATION = 1 << 9, // next \] leaves the loop
319 FLAG_SIMPLE2 = 1 << 10, // next \) leaves the loop
320 FLAG_OPTION = 1 << 11, // read [...] style option
321 FLAG_BRACED = 1 << 12 // read {...} style argument
326 // Helper class for parsing
332 Token() : cs_(), char_(0), cat_(catIgnore) {}
334 Token(char_type c, CatCode cat) : cs_(), char_(c), cat_(cat) {}
336 explicit Token(docstring const & cs) : cs_(cs), char_(0), cat_(catIgnore) {}
339 docstring const & cs() const { return cs_; }
341 CatCode cat() const { return cat_; }
343 char_type character() const { return char_; }
345 docstring asString() const { return !cs_.empty() ? cs_ : docstring(1, char_); }
347 docstring asInput() const { return !cs_.empty() ? '\\' + cs_ : docstring(1, char_); }
359 ostream & operator<<(ostream & os, Token const & t)
361 if (!t.cs().empty()) {
362 docstring const & cs = t.cs();
363 // FIXME: For some strange reason, the stream operator instantiate
364 // a new Token before outputting the contents of t.cs().
365 // Because of this the line
367 // below becomes recursive.
368 // In order to avoid that we return early:
371 os << '\\' << to_utf8(cs);
373 else if (t.cat() == catLetter)
376 os << '[' << t.character() << ',' << t.cat() << ']';
384 typedef InsetMath::mode_type mode_type;
386 typedef Parse::flags parse_mode;
389 Parser(Lexer & lex, parse_mode mode, Buffer * buf);
390 /// Only use this for reading from .lyx file format, for the reason
391 /// see Parser::tokenize(istream &).
392 Parser(istream & is, parse_mode mode, Buffer * buf);
394 Parser(docstring const & str, parse_mode mode, Buffer * buf);
397 bool parse(MathAtom & at);
399 bool parse(MathData & array, unsigned flags, mode_type mode);
401 bool parse1(InsetMathGrid & grid, unsigned flags, mode_type mode,
404 int lineno() const { return lineno_; }
407 /// store current position
409 /// restore previous position
411 /// forget last saved position
416 void parse2(MathAtom & at, unsigned flags, mode_type mode, bool numbered);
417 /// get arg delimited by 'left' and 'right'
418 docstring getArg(char_type left, char_type right);
422 void error(string const & msg);
423 void error(docstring const & msg) { error(to_utf8(msg)); }
424 /// dump contents to screen
426 /// Only use this for reading from .lyx file format (see
427 /// implementation for reason)
428 void tokenize(istream & is);
430 void tokenize(docstring const & s);
432 void skipSpaceTokens(idocstream & is, char_type c);
434 void push_back(Token const & t);
436 Token const & prevToken() const;
438 Token const & nextToken() const;
440 Token const & getToken();
441 /// skips spaces if any
444 void lex(docstring const & s);
448 docstring parse_verbatim_item();
450 docstring parse_verbatim_option();
455 vector<Token> tokens_;
459 std::vector<unsigned> positions_;
460 /// Stack of active environments
461 vector<docstring> environments_;
471 Parser::Parser(Lexer & lexer, parse_mode mode, Buffer * buf)
472 : lineno_(lexer.lineNumber()), pos_(0), mode_(mode), success_(true),
475 tokenize(lexer.getStream());
480 Parser::Parser(istream & is, parse_mode mode, Buffer * buf)
481 : lineno_(0), pos_(0), mode_(mode), success_(true), buffer_(buf)
487 Parser::Parser(docstring const & str, parse_mode mode, Buffer * buf)
488 : lineno_(0), pos_(0), mode_(mode), success_(true), buffer_(buf)
494 void Parser::push_back(Token const & t)
496 tokens_.push_back(t);
500 Token const & Parser::prevToken() const
502 static const Token dummy;
503 return pos_ > 0 ? tokens_[pos_ - 1] : dummy;
507 Token const & Parser::nextToken() const
509 static const Token dummy;
510 return good() ? tokens_[pos_] : dummy;
514 Token const & Parser::getToken()
516 static const Token dummy;
517 //lyxerr << "looking at token " << tokens_[pos_] << " pos: " << pos_ << endl;
518 return good() ? tokens_[pos_++] : dummy;
522 void Parser::skipSpaces()
524 while (nextToken().cat() == catSpace || nextToken().cat() == catNewline)
529 void Parser::putback()
535 void Parser::pushPosition()
537 positions_.push_back(pos_);
541 void Parser::popPosition()
543 pos_ = positions_.back();
544 positions_.pop_back();
548 void Parser::dropPosition()
550 positions_.pop_back();
554 bool Parser::good() const
556 return pos_ < tokens_.size();
560 char_type Parser::getChar()
563 error("The input stream is not well...");
566 return tokens_[pos_++].character();
570 docstring Parser::getArg(char_type left, char_type right)
578 char_type c = getChar();
583 while ((c = getChar()) != right && good())
590 void Parser::skipSpaceTokens(idocstream & is, char_type c)
592 // skip trailing spaces
593 while (catcode(c) == catSpace || catcode(c) == catNewline)
596 //lyxerr << "putting back: " << c << endl;
601 void Parser::tokenize(istream & is)
603 // eat everything up to the next \end_inset or end of stream
604 // and store it in s for further tokenization
609 if (s.size() >= 10 && s.substr(s.size() - 10) == "\\end_inset") {
610 s = s.substr(0, s.size() - 10);
614 // Remove the space after \end_inset
615 if (is.get(c) && c != ' ')
619 tokenize(from_utf8(s));
623 void Parser::tokenize(docstring const & buffer)
625 idocstringstream is((mode_ & Parse::VERBATIM)
626 ? escapeSpecialChars(buffer, mode_ & Parse::TEXTMODE)
627 : buffer, ios::in | ios::binary);
631 //lyxerr << "reading c: " << c << endl;
633 switch (catcode(c)) {
637 if (catcode(c) == catNewline)
638 ; //push_back(Token("par"));
640 push_back(Token('\n', catNewline));
648 while (is.get(c) && catcode(c) != catNewline)
658 error("unexpected end of input");
663 if (catcode(c) == catLetter) {
665 while (is.get(c) && catcode(c) == catLetter)
667 skipSpaceTokens(is, c);
676 push_back(Token(c, catcode(c)));
678 skipSpaceTokens(is, c);
683 if (!(mode_ & Parse::QUIET))
684 lyxerr << "ignoring a char: " << int(c) << endl;
689 push_back(Token(c, catcode(c)));
699 void Parser::dump() const
701 lyxerr << "\nTokens: ";
702 for (unsigned i = 0; i < tokens_.size(); ++i) {
705 lyxerr << tokens_[i];
707 lyxerr << " pos: " << pos_ << endl;
711 void Parser::error(string const & msg)
714 if (!(mode_ & Parse::QUIET)) {
715 lyxerr << "Line ~" << lineno_ << ": Math parse error: "
722 bool Parser::parse(MathAtom & at)
725 MathData ar(buffer_);
726 parse(ar, false, InsetMath::UNDECIDED_MODE);
727 if (ar.size() != 1 || ar.front()->getType() == hullNone) {
728 if (!(mode_ & Parse::QUIET))
729 lyxerr << "unusual contents found: " << ar << endl;
730 at = MathAtom(new InsetMathPar(buffer_, ar));
731 //if (at->nargs() > 0)
732 // at.nucleus()->cell(0) = ar;
734 // lyxerr << "unusual contents found: " << ar << endl;
742 docstring Parser::parse_verbatim_option()
746 if (nextToken().character() == '[') {
749 for (Token t = getToken(); t.character() != ']' && good(); t = getToken()) {
750 if (t.cat() == catBegin) {
752 res += '{' + parse_verbatim_item() + '}';
761 docstring Parser::parse_verbatim_item()
765 if (nextToken().cat() == catBegin) {
768 for (Token t = getToken(); t.cat() != catEnd && good(); t = getToken()) {
769 if (t.cat() == catBegin) {
771 res += '{' + parse_verbatim_item() + '}';
781 bool Parser::parse(MathData & array, unsigned flags, mode_type mode)
783 InsetMathGrid grid(buffer_, 1, 1);
784 parse1(grid, flags, mode, false);
785 array = grid.cell(0);
790 void Parser::parse2(MathAtom & at, const unsigned flags, const mode_type mode,
793 parse1(*(at.nucleus()->asGridInset()), flags, mode, numbered);
797 bool Parser::parse1(InsetMathGrid & grid, unsigned flags,
798 const mode_type mode, const bool numbered)
800 InsetMathGrid::row_type cellrow = 0;
801 InsetMathGrid::col_type cellcol = 0;
802 MathData * cell = &grid.cell(grid.index(cellrow, cellcol));
803 Buffer * buf = buffer_;
805 if (grid.asHullInset())
806 grid.asHullInset()->numbered(cellrow, numbered);
809 //lyxerr << " flags: " << flags << endl;
810 //lyxerr << " mode: " << mode << endl;
811 //lyxerr << "grid: " << grid << endl;
814 Token const & t = getToken();
817 lyxerr << "t: " << t << " flags: " << flags << endl;
818 lyxerr << "mode: " << mode << endl;
823 if (flags & FLAG_ITEM) {
825 if (t.cat() == catBegin) {
826 // skip the brace and collect everything to the next matching
828 parse1(grid, FLAG_BRACE_LAST, mode, numbered);
832 // handle only this single token, leave the loop if done
837 if (flags & FLAG_BRACED) {
838 if (t.cat() == catSpace)
841 if (t.cat() != catBegin) {
842 error("opening brace expected");
846 // skip the brace and collect everything to the next matching
848 flags = FLAG_BRACE_LAST;
852 if (flags & FLAG_OPTION) {
853 if (t.cat() == catOther && t.character() == '[') {
855 parse(ar, FLAG_BRACK_LAST, mode);
858 // no option found, put back token and we are done
867 if (t.cat() == catMath) {
868 if (mode != InsetMath::MATH_MODE) {
869 // we are inside some text mode thingy, so opening new math is allowed
870 Token const & n = getToken();
871 if (n.cat() == catMath) {
872 // TeX's $$...$$ syntax for displayed math
873 if (mode == InsetMath::UNDECIDED_MODE) {
874 cell->push_back(MathAtom(new InsetMathHull(buf, hullEquation)));
875 parse2(cell->back(), FLAG_SIMPLE, InsetMath::MATH_MODE, false);
876 getToken(); // skip the second '$' token
878 // This is not an outer hull and display math is
879 // not allowed inside text mode environments.
880 error("bad math environment $$");
884 // simple $...$ stuff
886 if (mode == InsetMath::UNDECIDED_MODE) {
887 cell->push_back(MathAtom(new InsetMathHull(buf, hullSimple)));
888 parse2(cell->back(), FLAG_SIMPLE, InsetMath::MATH_MODE, false);
890 // Don't create nested math hulls (bug #5392)
891 cell->push_back(MathAtom(new InsetMathEnsureMath(buf)));
892 parse(cell->back().nucleus()->cell(0), FLAG_SIMPLE, InsetMath::MATH_MODE);
897 else if (flags & FLAG_SIMPLE) {
898 // this is the end of the formula
903 Token const & n = getToken();
904 if (n.cat() == catMath) {
905 error("something strange in the parser");
908 // This is inline math ($...$), but the parser thinks we are
909 // already in math mode and latex would issue an error, unless we
910 // are inside a text mode user macro. We have no way to tell, so
911 // let's play safe by using \ensuremath, as it will work in any case.
913 cell->push_back(MathAtom(new InsetMathEnsureMath(buf)));
914 parse(cell->back().nucleus()->cell(0), FLAG_SIMPLE, InsetMath::MATH_MODE);
919 else if (t.cat() == catLetter)
920 cell->push_back(MathAtom(new InsetMathChar(t.character())));
922 else if (t.cat() == catSpace && mode != InsetMath::MATH_MODE) {
923 if (cell->empty() || cell->back()->getChar() != ' ')
924 cell->push_back(MathAtom(new InsetMathChar(t.character())));
927 else if (t.cat() == catNewline && mode != InsetMath::MATH_MODE) {
928 if (cell->empty() || cell->back()->getChar() != ' ')
929 cell->push_back(MathAtom(new InsetMathChar(' ')));
932 else if (t.cat() == catParameter) {
933 Token const & n = nextToken();
934 char_type c = n.character();
935 if (c && '0' < c && c <= '9') {
936 cell->push_back(MathAtom(new InsetMathMacroArgument(c - '0')));
939 cell->push_back(MathAtom(new InsetMathHash()));
942 else if (t.cat() == catActive)
943 cell->push_back(MathAtom(new InsetMathSpace(string(1, t.character()), "")));
945 else if (t.cat() == catBegin) {
947 parse(ar, FLAG_BRACE_LAST, mode);
948 // do not create a BraceInset if they were written by LyX
949 // this helps to keep the annoyance of "a choose b" to a minimum
950 if (ar.size() == 1 && ar[0]->extraBraces())
953 cell->push_back(MathAtom(new InsetMathBrace(ar)));
956 else if (t.cat() == catEnd) {
957 if (flags & FLAG_BRACE_LAST)
959 error("found '}' unexpectedly");
960 //LASSERT(false, /**/);
961 //add(cell, '}', LM_TC_TEX);
964 else if (t.cat() == catAlign) {
965 //lyxerr << " column now " << (cellcol + 1)
966 // << " max: " << grid.ncols() << endl;
967 if (flags & FLAG_ALIGN)
969 if (addCol(grid, cellcol))
970 cell = &grid.cell(grid.index(cellrow, cellcol));
973 else if (t.cat() == catSuper || t.cat() == catSub) {
974 bool up = (t.cat() == catSuper);
975 // we need no new script inset if the last thing was a scriptinset,
976 // which has that script already not the same script already
978 cell->push_back(MathAtom(new InsetMathScript(buf, up)));
979 else if (cell->back()->asScriptInset() &&
980 !cell->back()->asScriptInset()->has(up))
981 cell->back().nucleus()->asScriptInset()->ensure(up);
982 else if (cell->back()->asScriptInset())
983 cell->push_back(MathAtom(new InsetMathScript(buf, up)));
985 cell->back() = MathAtom(new InsetMathScript(buf, cell->back(), up));
986 InsetMathScript * p = cell->back().nucleus()->asScriptInset();
987 // special handling of {}-bases
988 // Here we could remove the brace inset for things
989 // like {a'}^2 and add the braces back in
990 // InsetMathScript::write().
991 // We do not do it, since it is not possible to detect
992 // reliably whether the braces are needed because the
993 // nucleus contains more than one symbol, or whether
994 // they are needed for unknown commands like \xx{a}_0
995 // or \yy{a}{b}_0. This was done in revision 14819
996 // in an unreliable way. See this thread
997 // http://www.mail-archive.com/lyx-devel%40lists.lyx.org/msg104917.html
999 // However, we remove empty braces because they look
1000 // ugly on screen and we are sure that they were added
1001 // by the write() method (and will be re-added on save).
1002 if (p->nuc().size() == 1 &&
1003 p->nuc().back()->asBraceInset() &&
1004 p->nuc().back()->asBraceInset()->cell(0).empty())
1007 parse(p->cell(p->idxOfScript(up)), FLAG_ITEM, mode);
1010 else if (t.character() == ']' && (flags & FLAG_BRACK_LAST)) {
1011 //lyxerr << "finished reading option" << endl;
1015 else if (t.cat() == catOther) {
1016 char_type c = t.character();
1017 if (!Encodings::isUnicodeTextOnly(c)
1018 || mode_ & Parse::VERBATIM
1019 || !(mode_ & Parse::USETEXT)
1020 || mode == InsetMath::TEXT_MODE) {
1021 cell->push_back(MathAtom(new InsetMathChar(c)));
1023 MathAtom at = createInsetMath("text", buf);
1024 at.nucleus()->cell(0).push_back(MathAtom(new InsetMathChar(c)));
1025 while (nextToken().cat() == catOther
1026 && Encodings::isUnicodeTextOnly(nextToken().character())) {
1027 c = getToken().character();
1028 at.nucleus()->cell(0).push_back(MathAtom(new InsetMathChar(c)));
1030 cell->push_back(at);
1034 else if (t.cat() == catComment) {
1037 Token const & tt = getToken();
1038 if (tt.cat() == catNewline)
1042 cell->push_back(MathAtom(new InsetMathComment(buf, s)));
1047 // control sequences
1050 else if (t.cs() == "lyxlock") {
1052 cell->back().nucleus()->lock(true);
1055 else if ((t.cs() == "global" && nextToken().cs() == "def") ||
1057 if (t.cs() == "global")
1061 docstring name = getToken().cs();
1066 while (good() && nextToken().cat() != catBegin) {
1067 pars += getToken().cs();
1074 parse(def, FLAG_ITEM, InsetMath::UNDECIDED_MODE);
1076 // is a version for display attached?
1079 if (nextToken().cat() == catBegin)
1080 parse(display, FLAG_ITEM, InsetMath::MATH_MODE);
1082 cell->push_back(MathAtom(new InsetMathMacroTemplate(buf,
1083 name, nargs, 0, MacroTypeDef,
1084 vector<MathData>(), def, display)));
1086 if (buf && (mode_ & Parse::TRACKMACRO))
1087 buf->usermacros.insert(name);
1090 else if (t.cs() == "newcommand" ||
1091 t.cs() == "renewcommand" ||
1092 t.cs() == "newlyxcommand") {
1094 if (getToken().cat() != catBegin) {
1095 error("'{' in \\newcommand expected (1) ");
1098 docstring name = getToken().cs();
1099 if (getToken().cat() != catEnd) {
1100 error("'}' in \\newcommand expected");
1105 docstring const arg = getArg('[', ']');
1108 nargs = convert<int>(arg);
1110 // optional argument given?
1113 vector<MathData> optionalValues;
1114 while (nextToken().character() == '[') {
1116 optionalValues.push_back(MathData());
1117 parse(optionalValues[optionals], FLAG_BRACK_LAST, mode);
1122 parse(def, FLAG_ITEM, InsetMath::UNDECIDED_MODE);
1124 // is a version for display attached?
1127 if (nextToken().cat() == catBegin)
1128 parse(display, FLAG_ITEM, InsetMath::MATH_MODE);
1130 cell->push_back(MathAtom(new InsetMathMacroTemplate(buf,
1131 name, nargs, optionals, MacroTypeNewcommand,
1132 optionalValues, def, display)));
1134 if (buf && (mode_ & Parse::TRACKMACRO))
1135 buf->usermacros.insert(name);
1138 else if (t.cs() == "newcommandx" ||
1139 t.cs() == "renewcommandx") {
1140 // \newcommandx{\foo}[2][usedefault, addprefix=\global,1=default]{#1,#2}
1143 if (nextToken().cat() == catBegin) {
1145 name = getToken().cs();
1146 if (getToken().cat() != catEnd) {
1147 error("'}' in \\newcommandx expected");
1151 name = getToken().cs();
1154 docstring const arg = getArg('[', ']');
1156 error("[num] in \\newcommandx expected");
1159 int nargs = convert<int>(arg);
1163 vector<MathData> optionalValues;
1164 if (nextToken().character() == '[') {
1168 // handle 'opt=value' options, separated by ','.
1170 while (nextToken().character() != ']' && good()) {
1171 if (nextToken().character() >= '1'
1172 && nextToken().character() <= '9') {
1173 // optional value -> get parameter number
1174 int n = getChar() - '0';
1176 error("Arity of \\newcommandx too low "
1177 "for given optional parameter.");
1182 if (getToken().character() != '=') {
1183 error("'=' and optional parameter value "
1184 "expected for \\newcommandx");
1189 int optNum = max(size_t(n), optionalValues.size());
1190 optionalValues.resize(optNum);
1191 optionalValues[n - 1].clear();
1192 while (nextToken().character() != ']'
1193 && nextToken().character() != ',') {
1195 parse(data, FLAG_ITEM, InsetMath::UNDECIDED_MODE);
1196 optionalValues[n - 1].append(data);
1198 optionals = max(n, optionals);
1199 } else if (nextToken().cat() == catLetter) {
1200 // we in fact ignore every non-optional
1205 while (nextToken().cat() == catLetter)
1211 if (nextToken().character() == '=') {
1213 while (nextToken().character() != ']'
1214 && nextToken().character() != ',')
1215 parse(value, FLAG_ITEM,
1216 InsetMath::UNDECIDED_MODE);
1219 error("option for \\newcommandx expected");
1225 if (nextToken().character() == ',') {
1228 } else if (nextToken().character() != ']') {
1229 error("Expecting ',' or ']' in options "
1230 "of \\newcommandx");
1243 parse(def, FLAG_ITEM, InsetMath::UNDECIDED_MODE);
1245 // is a version for display attached?
1248 if (nextToken().cat() == catBegin)
1249 parse(display, FLAG_ITEM, InsetMath::MATH_MODE);
1251 cell->push_back(MathAtom(new InsetMathMacroTemplate(buf,
1252 name, nargs, optionals, MacroTypeNewcommandx,
1253 optionalValues, def, display)));
1255 if (buf && (mode_ & Parse::TRACKMACRO))
1256 buf->usermacros.insert(name);
1259 else if (t.cs() == "(") {
1260 if (mode == InsetMath::UNDECIDED_MODE) {
1261 cell->push_back(MathAtom(new InsetMathHull(buf, hullSimple)));
1262 parse2(cell->back(), FLAG_SIMPLE2, InsetMath::MATH_MODE, false);
1264 // Don't create nested math hulls (bug #5392)
1265 cell->push_back(MathAtom(new InsetMathEnsureMath(buf)));
1266 parse(cell->back().nucleus()->cell(0), FLAG_SIMPLE2, InsetMath::MATH_MODE);
1270 else if (t.cs() == "[") {
1271 if (mode != InsetMath::UNDECIDED_MODE) {
1272 error("bad math environment [");
1275 cell->push_back(MathAtom(new InsetMathHull(buf, hullEquation)));
1276 parse2(cell->back(), FLAG_EQUATION, InsetMath::MATH_MODE, false);
1279 else if (t.cs() == "protect")
1280 // ignore \\protect, will hopefully be re-added during output
1283 else if (t.cs() == "end") {
1284 if (flags & FLAG_END) {
1285 // eat environment name
1286 docstring const name = getArg('{', '}');
1287 if (environments_.empty())
1288 error("'found \\end{" + name +
1289 "}' without matching '\\begin{" +
1291 else if (name != environments_.back())
1292 error("'\\end{" + name +
1293 "}' does not match '\\begin{" +
1294 environments_.back() + "}'");
1296 environments_.pop_back();
1297 // Delete empty last row in matrix
1299 // If you abuse InsetMathGrid for
1300 // non-matrix like structures you
1301 // probably need to refine this test.
1302 // Right now we only have to test for
1303 // single line hull insets.
1304 if (grid.nrows() > 1 && innerHull(name))
1305 delEmptyLastRow(grid);
1309 error("found 'end' unexpectedly");
1312 else if (t.cs() == ")") {
1313 if (flags & FLAG_SIMPLE2)
1315 error("found '\\)' unexpectedly");
1318 else if (t.cs() == "]") {
1319 if (flags & FLAG_EQUATION)
1321 error("found '\\]' unexpectedly");
1324 else if (t.cs() == "\\") {
1325 if (flags & FLAG_ALIGN)
1327 bool starred = false;
1329 if (nextToken().asInput() == "*") {
1332 } else if (nextToken().asInput() == "[")
1333 arg = getArg('[', ']');
1335 error("missing token after \\\\");
1336 // skip "{}" added in front of "[" (the
1337 // counterpart is in InsetMathGrid::eolString())
1338 // skip spaces because formula could come from tex2lyx
1339 bool skipBraces = false;
1341 if (nextToken().cat() == catBegin) {
1343 if (nextToken().cat() == catEnd) {
1347 if (nextToken().asInput() == "[")
1356 bool const added = addRow(grid, cellrow, arg, !starred);
1359 if (grid.asHullInset())
1360 grid.asHullInset()->numbered(
1362 cell = &grid.cell(grid.index(cellrow,
1367 else if (t.cs() == "multicolumn" && grid.handlesMulticolumn()) {
1368 // if the columns are specified numerically,
1369 // extract column count and insert dummy cells,
1370 // otherwise parse it as an user macro
1372 parse(count, FLAG_ITEM, mode);
1374 // limit arbitrarily to 100 columns
1375 if (extractNumber(count, cols) && cols > 0 && cols < 100) {
1376 // resize the table if necessary
1377 size_t first = grid.index(cellrow, cellcol);
1378 for (int i = 1; i < cols; ++i) {
1379 if (addCol(grid, cellcol)) {
1380 size_t const idx = grid.index(cellrow, cellcol);
1381 grid.cellinfo(idx).multi =
1382 InsetMathGrid::CELL_PART_OF_MULTICOLUMN;
1386 // the first cell is the real thing, not a dummy
1387 cell = &grid.cell(first);
1388 grid.cellinfo(first).multi =
1389 InsetMathGrid::CELL_BEGIN_OF_MULTICOLUMN;
1391 // read special alignment
1393 parse(align, FLAG_ITEM, mode);
1394 grid.cellinfo(first).align = asString(align);
1396 // parse the remaining contents into the "real" cell
1397 parse(*cell, FLAG_ITEM, mode);
1399 MathAtom at = MathAtom(new InsetMathMacro(buf, t.cs()));
1400 cell->push_back(at);
1401 cell->push_back(MathAtom(new InsetMathBrace(count)));
1405 else if (t.cs() == "limits" || t.cs() == "nolimits") {
1407 cell->back()->limits(t.cs() == "limits" ? LIMITS : NO_LIMITS);
1409 MathAtom at = createInsetMath(t.cs(), buf);
1410 cell->push_back(at);
1414 // \notag is the same as \nonumber if amsmath is used
1415 else if ((t.cs() == "nonumber" || t.cs() == "notag") &&
1417 grid.asHullInset()->numbered(cellrow, false);
1419 else if (t.cs() == "number" && grid.asHullInset())
1420 grid.asHullInset()->numbered(cellrow, true);
1422 else if (t.cs() == "hline") {
1423 grid.rowinfo(cellrow).lines++;
1426 else if (t.cs() == "sqrt") {
1428 parse(ar, FLAG_OPTION, mode);
1430 cell->push_back(MathAtom(new InsetMathRoot(buf)));
1431 cell->back().nucleus()->cell(1) = ar;
1433 cell->push_back(MathAtom(new InsetMathSqrt(buf)));
1434 parse(cell->back().nucleus()->cell(0), FLAG_ITEM, mode);
1437 else if (t.cs() == "cancelto") {
1439 parse(ar, FLAG_ITEM, mode);
1440 cell->push_back(MathAtom(new InsetMathCancelto(buf)));
1441 cell->back().nucleus()->cell(1) = ar;
1442 parse(cell->back().nucleus()->cell(0), FLAG_ITEM, mode);
1445 else if (t.cs() == "unit") {
1446 // Allowed formats \unit[val]{unit}
1448 parse(ar, FLAG_OPTION, mode);
1450 cell->push_back(MathAtom(new InsetMathFrac(buf, InsetMathFrac::UNIT)));
1451 cell->back().nucleus()->cell(0) = ar;
1452 parse(cell->back().nucleus()->cell(1), FLAG_ITEM, mode);
1454 cell->push_back(MathAtom(new InsetMathFrac(buf, InsetMathFrac::UNIT, 1)));
1455 parse(cell->back().nucleus()->cell(0), FLAG_ITEM, mode);
1459 else if (t.cs() == "unitfrac") {
1460 // Here allowed formats are \unitfrac[val]{num}{denom}
1462 parse(ar, FLAG_OPTION, mode);
1464 cell->push_back(MathAtom(new InsetMathFrac(buf, InsetMathFrac::UNITFRAC, 3)));
1465 cell->back().nucleus()->cell(2) = ar;
1467 cell->push_back(MathAtom(new InsetMathFrac(buf, InsetMathFrac::UNITFRAC)));
1469 parse(cell->back().nucleus()->cell(0), FLAG_ITEM, mode);
1470 parse(cell->back().nucleus()->cell(1), FLAG_ITEM, mode);
1473 else if (t.cs() == "cfrac") {
1474 // allowed formats are \cfrac[pos]{num}{denom}
1475 docstring const arg = getArg('[', ']');
1476 //lyxerr << "got so far: '" << arg << "'" << endl;
1478 cell->push_back(MathAtom(new InsetMathFrac(buf, InsetMathFrac::CFRACLEFT)));
1479 else if (arg == "r")
1480 cell->push_back(MathAtom(new InsetMathFrac(buf, InsetMathFrac::CFRACRIGHT)));
1481 else if (arg.empty() || arg == "c")
1482 cell->push_back(MathAtom(new InsetMathFrac(buf, InsetMathFrac::CFRAC)));
1484 error("found invalid optional argument");
1487 parse(cell->back().nucleus()->cell(0), FLAG_ITEM, mode);
1488 parse(cell->back().nucleus()->cell(1), FLAG_ITEM, mode);
1491 else if (t.cs() == "sideset") {
1492 // Here allowed formats are \sideset{_{bl}^{tl}}{_{br}^{tr}}{operator}
1494 InsetMathScript * script[2] = {0, 0};
1495 for (int i = 0; i < 2; ++i) {
1496 parse(ar[i], FLAG_ITEM, mode);
1497 if (ar[i].size() == 1)
1498 script[i] = ar[i][0].nucleus()->asScriptInset();
1500 bool const hasscript[2] = {script[0] ? true : false, script[1] ? true : false};
1501 cell->push_back(MathAtom(new InsetMathSideset(buf, hasscript[0], hasscript[1])));
1503 if (script[0]->hasDown())
1504 cell->back().nucleus()->cell(1) = script[0]->down();
1505 if (script[0]->hasUp())
1506 cell->back().nucleus()->cell(2) = script[0]->up();
1508 cell->back().nucleus()->cell(1) = ar[0];
1510 if (script[1]->hasDown())
1511 cell->back().nucleus()->cell(2 + hasscript[0]) = script[1]->down();
1512 if (script[1]->hasUp())
1513 cell->back().nucleus()->cell(3 + hasscript[0]) = script[1]->up();
1515 cell->back().nucleus()->cell(2 + hasscript[0]) = ar[1];
1516 parse(cell->back().nucleus()->cell(0), FLAG_ITEM, mode);
1519 else if (t.cs() == "stackrel") {
1520 // Here allowed formats are \stackrel[subscript]{superscript}{operator}
1522 parse(ar, FLAG_OPTION, mode);
1523 cell->push_back(MathAtom(new InsetMathStackrel(buf, !ar.empty())));
1525 cell->back().nucleus()->cell(2) = ar;
1526 parse(cell->back().nucleus()->cell(1), FLAG_ITEM, mode);
1527 parse(cell->back().nucleus()->cell(0), FLAG_ITEM, mode);
1530 else if (t.cs() == "xrightarrow" || t.cs() == "xleftarrow") {
1531 cell->push_back(createInsetMath(t.cs(), buf));
1532 parse(cell->back().nucleus()->cell(1), FLAG_OPTION, mode);
1533 parse(cell->back().nucleus()->cell(0), FLAG_ITEM, mode);
1536 else if (t.cs() == "xhookrightarrow" || t.cs() == "xhookleftarrow" ||
1537 t.cs() == "xRightarrow" || t.cs() == "xLeftarrow" ||
1538 t.cs() == "xleftrightarrow" || t.cs() == "xLeftrightarrow" ||
1539 t.cs() == "xrightharpoondown" || t.cs() == "xrightharpoonup" ||
1540 t.cs() == "xleftharpoondown" || t.cs() == "xleftharpoonup" ||
1541 t.cs() == "xleftrightharpoons" || t.cs() == "xrightleftharpoons" ||
1542 t.cs() == "xmapsto") {
1543 cell->push_back(createInsetMath(t.cs(), buf));
1544 parse(cell->back().nucleus()->cell(1), FLAG_OPTION, mode);
1545 parse(cell->back().nucleus()->cell(0), FLAG_ITEM, mode);
1548 else if (t.cs() == "ref" || t.cs() == "eqref" || t.cs() == "prettyref"
1549 || t.cs() == "nameref" || t.cs() == "pageref"
1550 || t.cs() == "vpageref" || t.cs() == "vref") {
1551 cell->push_back(MathAtom(new InsetMathRef(buf, t.cs())));
1552 docstring const opt = parse_verbatim_option();
1553 docstring const ref = parse_verbatim_item();
1555 cell->back().nucleus()->cell(1).push_back(
1556 MathAtom(new InsetMathString(opt)));
1558 cell->back().nucleus()->cell(0).push_back(
1559 MathAtom(new InsetMathString(ref)));
1562 else if (t.cs() == "left") {
1564 Token const & tl = getToken();
1565 // \| and \Vert are equivalent, and InsetMathDelim
1567 // FIXME: fix this in InsetMathDelim itself!
1568 docstring const l = tl.cs() == "|" ? from_ascii("Vert") : tl.asString();
1570 parse(ar, FLAG_RIGHT, mode);
1574 Token const & tr = getToken();
1575 docstring const r = tr.cs() == "|" ? from_ascii("Vert") : tr.asString();
1576 cell->push_back(MathAtom(new InsetMathDelim(buf, l, r, ar)));
1579 else if (t.cs() == "right") {
1580 if (flags & FLAG_RIGHT)
1582 //lyxerr << "got so far: '" << cell << "'" << endl;
1583 error("Unmatched right delimiter");
1587 else if (t.cs() == "begin") {
1588 docstring const name = getArg('{', '}');
1592 error("found invalid environment");
1596 environments_.push_back(name);
1598 if (name == "array" || name == "subarray") {
1599 docstring const valign = parse_verbatim_option() + 'c';
1600 docstring const halign = parse_verbatim_item();
1601 cell->push_back(MathAtom(new InsetMathArray(buf, name,
1602 InsetMathGrid::guessColumns(halign), 1, (char)valign[0], halign)));
1603 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, false);
1606 else if (name == "tabular") {
1607 docstring const valign = parse_verbatim_option() + 'c';
1608 docstring const halign = parse_verbatim_item();
1609 cell->push_back(MathAtom(new InsetMathTabular(buf, name,
1610 InsetMathGrid::guessColumns(halign), 1, (char)valign[0], halign)));
1611 parse2(cell->back(), FLAG_END, InsetMath::TEXT_MODE, false);
1614 else if (name == "split" || name == "cases") {
1615 cell->push_back(createInsetMath(name, buf));
1616 parse2(cell->back(), FLAG_END, mode, false);
1619 else if (name == "alignedat") {
1620 docstring const valign = parse_verbatim_option() + 'c';
1621 // ignore this for a while
1623 cell->push_back(MathAtom(new InsetMathSplit(buf, name, (char)valign[0])));
1624 parse2(cell->back(), FLAG_END, mode, false);
1627 else if (name == "math") {
1628 if (mode == InsetMath::UNDECIDED_MODE) {
1629 cell->push_back(MathAtom(new InsetMathHull(buf, hullSimple)));
1630 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, false);
1632 // Don't create nested math hulls (bug #5392)
1633 cell->push_back(MathAtom(new InsetMathEnsureMath(buf)));
1634 parse(cell->back().nucleus()->cell(0), FLAG_END, InsetMath::MATH_MODE);
1638 else if (name == "equation" || name == "equation*"
1639 || name == "displaymath") {
1640 if (mode != InsetMath::UNDECIDED_MODE) {
1641 error("bad math environment " + name);
1644 cell->push_back(MathAtom(new InsetMathHull(buf, hullEquation)));
1645 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, (name == "equation"));
1648 else if (name == "eqnarray" || name == "eqnarray*") {
1649 if (mode != InsetMath::UNDECIDED_MODE) {
1650 error("bad math environment " + name);
1653 cell->push_back(MathAtom(new InsetMathHull(buf, hullEqnArray)));
1654 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, !stared(name));
1657 else if (name == "align" || name == "align*") {
1658 if (mode == InsetMath::UNDECIDED_MODE) {
1659 cell->push_back(MathAtom(new InsetMathHull(buf, hullAlign)));
1660 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, !stared(name));
1662 cell->push_back(MathAtom(new InsetMathSplit(buf, name,
1663 'c', !stared(name))));
1664 parse2(cell->back(), FLAG_END, mode, !stared(name));
1668 else if (name == "flalign" || name == "flalign*") {
1669 if (mode != InsetMath::UNDECIDED_MODE) {
1670 error("bad math environment " + name);
1673 cell->push_back(MathAtom(new InsetMathHull(buf, hullFlAlign)));
1674 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, !stared(name));
1677 else if (name == "alignat" || name == "alignat*") {
1678 if (mode != InsetMath::UNDECIDED_MODE) {
1679 error("bad math environment " + name);
1682 // ignore this for a while
1684 cell->push_back(MathAtom(new InsetMathHull(buf, hullAlignAt)));
1685 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, !stared(name));
1688 else if (name == "xalignat" || name == "xalignat*") {
1689 if (mode != InsetMath::UNDECIDED_MODE) {
1690 error("bad math environment " + name);
1693 // ignore this for a while
1695 cell->push_back(MathAtom(new InsetMathHull(buf, hullXAlignAt)));
1696 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, !stared(name));
1699 else if (name == "xxalignat") {
1700 if (mode != InsetMath::UNDECIDED_MODE) {
1701 error("bad math environment " + name);
1704 // ignore this for a while
1706 cell->push_back(MathAtom(new InsetMathHull(buf, hullXXAlignAt)));
1707 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, !stared(name));
1710 else if (name == "multline" || name == "multline*") {
1711 if (mode != InsetMath::UNDECIDED_MODE) {
1712 error("bad math environment " + name);
1715 cell->push_back(MathAtom(new InsetMathHull(buf, hullMultline)));
1716 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, !stared(name));
1719 else if (name == "gather" || name == "gather*") {
1720 if (mode != InsetMath::UNDECIDED_MODE) {
1721 error("bad math environment " + name);
1724 cell->push_back(MathAtom(new InsetMathHull(buf, hullGather)));
1725 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, !stared(name));
1728 else if (latexkeys const * l = in_word_set(name)) {
1729 if (l->inset == "matrix") {
1730 cell->push_back(createInsetMath(name, buf));
1731 parse2(cell->back(), FLAG_END, mode, false);
1732 } else if (l->inset == "split") {
1733 docstring const valign = parse_verbatim_option() + 'c';
1734 cell->push_back(MathAtom(
1735 new InsetMathSplit(buf, name, (char)valign[0])));
1736 parse2(cell->back(), FLAG_END, mode, false);
1739 if (!(mode_ & Parse::QUIET)) {
1741 lyxerr << "found math environment `"
1743 << "' in symbols file with unsupported inset `"
1747 // create generic environment inset
1748 cell->push_back(MathAtom(new InsetMathEnv(buf, name)));
1749 parse(cell->back().nucleus()->cell(0), FLAG_END, mode);
1755 if (!(mode_ & Parse::QUIET) &&
1756 !(mode_ & Parse::TRACKMACRO)) {
1758 lyxerr << "found unknown math environment '"
1759 << to_utf8(name) << "'" << endl;
1761 // create generic environment inset
1762 cell->push_back(MathAtom(new InsetMathEnv(buf, name)));
1763 parse(cell->back().nucleus()->cell(0), FLAG_END, mode);
1767 else if (t.cs() == "kern" || t.cs() == "mkern") {
1772 Token const & tt = getToken();
1776 while (num_tokens--)
1780 s += tt.character();
1781 if (isValidLength(to_utf8(s)))
1785 cell->push_back(MathAtom(new InsetMathMacro(buf, t.cs())));
1787 cell->push_back(MathAtom(new InsetMathKern(s)));
1790 else if (t.cs() == "label") {
1791 // FIXME: This is swallowed in inline formulas
1792 docstring label = parse_verbatim_item();
1795 if (grid.asHullInset()) {
1796 grid.asHullInset()->label(cellrow, label);
1797 grid.asHullInset()->numbered(cellrow, true);
1799 cell->push_back(createInsetMath(t.cs(), buf));
1800 cell->push_back(MathAtom(new InsetMathBrace(ar)));
1804 else if (t.cs() == "choose" || t.cs() == "over"
1805 || t.cs() == "atop" || t.cs() == "brace"
1806 || t.cs() == "brack") {
1807 MathAtom at = createInsetMath(t.cs(), buf);
1808 at.nucleus()->cell(0) = *cell;
1810 parse(at.nucleus()->cell(1), flags, mode);
1811 cell->push_back(at);
1815 else if (t.cs() == "color") {
1816 docstring const color = parse_verbatim_item();
1817 cell->push_back(MathAtom(new InsetMathColor(buf, true, color)));
1818 parse(cell->back().nucleus()->cell(0), flags, mode);
1822 else if (t.cs() == "textcolor") {
1823 docstring const color = parse_verbatim_item();
1824 cell->push_back(MathAtom(new InsetMathColor(buf, false, color)));
1825 parse(cell->back().nucleus()->cell(0), FLAG_ITEM, InsetMath::TEXT_MODE);
1828 else if (t.cs() == "normalcolor") {
1829 cell->push_back(createInsetMath(t.cs(), buf));
1830 parse(cell->back().nucleus()->cell(0), flags, mode);
1834 else if (t.cs() == "substack") {
1835 cell->push_back(createInsetMath(t.cs(), buf));
1836 parse2(cell->back(), FLAG_ITEM, mode, false);
1837 // Delete empty last row if present
1838 InsetMathGrid & subgrid =
1839 *(cell->back().nucleus()->asGridInset());
1840 if (subgrid.nrows() > 1)
1841 delEmptyLastRow(subgrid);
1844 else if (t.cs() == "xymatrix") {
1845 odocstringstream os;
1846 while (good() && nextToken().cat() != catBegin)
1847 os << getToken().asInput();
1848 cell->push_back(createInsetMath(t.cs() + os.str(), buf));
1849 parse2(cell->back(), FLAG_ITEM, mode, false);
1850 // Delete empty last row if present
1851 InsetMathGrid & subgrid =
1852 *(cell->back().nucleus()->asGridInset());
1853 if (subgrid.nrows() > 1)
1854 delEmptyLastRow(subgrid);
1857 else if (t.cs() == "Diagram") {
1858 odocstringstream os;
1859 while (good() && nextToken().cat() != catBegin)
1860 os << getToken().asInput();
1861 cell->push_back(createInsetMath(t.cs() + os.str(), buf));
1862 parse2(cell->back(), FLAG_ITEM, mode, false);
1865 else if (t.cs() == "framebox" || t.cs() == "makebox") {
1866 cell->push_back(createInsetMath(t.cs(), buf));
1867 parse(cell->back().nucleus()->cell(0), FLAG_OPTION, InsetMath::TEXT_MODE);
1868 parse(cell->back().nucleus()->cell(1), FLAG_OPTION, InsetMath::TEXT_MODE);
1869 parse(cell->back().nucleus()->cell(2), FLAG_ITEM, InsetMath::TEXT_MODE);
1872 else if (t.cs() == "tag") {
1873 if (nextToken().character() == '*') {
1875 cell->push_back(createInsetMath(t.cs() + '*', buf));
1877 cell->push_back(createInsetMath(t.cs(), buf));
1878 parse(cell->back().nucleus()->cell(0), FLAG_ITEM, InsetMath::TEXT_MODE);
1881 else if (t.cs() == "hspace") {
1882 bool const prot = nextToken().character() == '*';
1885 docstring const name = t.cs();
1886 docstring const arg = parse_verbatim_item();
1888 if (prot && arg == "\\fill")
1889 cell->push_back(MathAtom(new InsetMathSpace("hspace*{\\fill}", "")));
1890 else if (isValidLength(to_utf8(arg), &length))
1891 cell->push_back(MathAtom(new InsetMathSpace(length, prot)));
1893 // Since the Length class cannot use length variables
1894 // we must not create an InsetMathSpace.
1895 cell->push_back(MathAtom(new InsetMathMacro(buf, name)));
1897 mathed_parse_cell(ar, '{' + arg + '}', mode_);
1902 else if (t.cs() == "smash") {
1904 if (nextToken().asInput() == "[") {
1905 // Since the phantom inset cannot handle optional arguments
1906 // other than b and t, we must not create an InsetMathPhantom
1907 // if opt is different from b and t (bug 8967).
1908 docstring const opt = parse_verbatim_option();
1909 if (opt == "t" || opt == "b") {
1910 cell->push_back(createInsetMath(t.cs() + opt, buf));
1911 parse(cell->back().nucleus()->cell(0), FLAG_ITEM, mode);
1913 docstring const arg = parse_verbatim_item();
1914 cell->push_back(MathAtom(new InsetMathMacro(buf, t.cs())));
1916 mathed_parse_cell(ar, '[' + opt + ']', mode_);
1919 mathed_parse_cell(ar, '{' + arg + '}', mode_);
1924 cell->push_back(createInsetMath(t.cs(), buf));
1925 parse(cell->back().nucleus()->cell(0), FLAG_ITEM, mode);
1930 else if (t.cs() == "infer") {
1932 parse(ar, FLAG_OPTION, mode);
1933 cell->push_back(createInsetMath(t.cs(), buf));
1934 parse2(cell->back(), FLAG_ITEM, mode, false);
1938 else if (t.cs() == "lyxmathsym") {
1940 if (getToken().cat() != catBegin) {
1941 error("'{' expected in \\" + t.cs());
1946 CatCode cat = nextToken().cat();
1947 while (good() && (count || cat != catEnd)) {
1948 if (cat == catBegin)
1950 else if (cat == catEnd)
1952 cmd += getToken().asInput();
1953 cat = nextToken().cat();
1955 if (getToken().cat() != catEnd) {
1956 error("'}' expected in \\" + t.cs());
1962 cmd = Encodings::fromLaTeXCommand(cmd,
1963 Encodings::MATH_CMD | Encodings::TEXT_CMD,
1965 for (size_t i = 0; i < cmd.size(); ++i)
1966 cell->push_back(MathAtom(new InsetMathChar(cmd[i])));
1968 char_type c = rem[0];
1969 cell->push_back(MathAtom(new InsetMathChar(c)));
1970 cmd = rem.substr(1);
1974 } while (!cmd.empty());
1977 else if (!t.cs().empty()) {
1978 bool const no_mhchem =
1979 (t.cs() == "ce" || t.cs() == "cf")
1980 && buf && buf->params().use_package("mhchem") ==
1981 BufferParams::package_off;
1983 bool const is_user_macro = no_mhchem ||
1984 (buf && ((mode_ & Parse::TRACKMACRO)
1985 ? buf->usermacros.count(t.cs()) != 0
1986 : buf->getMacro(t.cs(), false) != 0));
1988 latexkeys const * l = in_word_set(t.cs());
1989 if (l && !is_user_macro) {
1990 if (l->inset == "big") {
1992 docstring const delim = getToken().asInput();
1993 if (InsetMathBig::isBigInsetDelim(delim))
1994 cell->push_back(MathAtom(
1995 new InsetMathBig(t.cs(), delim)));
1997 cell->push_back(createInsetMath(t.cs(), buf));
1998 // For some reason delim.empty()
1999 // is always false here
2005 else if (l->inset == "font") {
2006 cell->push_back(createInsetMath(t.cs(), buf));
2007 parse(cell->back().nucleus()->cell(0),
2008 FLAG_ITEM, asMode(mode, l->extra));
2011 else if (l->inset == "oldfont") {
2012 cell->push_back(createInsetMath(t.cs(), buf));
2013 parse(cell->back().nucleus()->cell(0),
2014 flags | FLAG_ALIGN, asMode(mode, l->extra));
2015 if (prevToken().cat() != catAlign &&
2016 prevToken().cs() != "\\")
2021 else if (l->inset == "style") {
2022 cell->push_back(createInsetMath(t.cs(), buf));
2023 parse(cell->back().nucleus()->cell(0),
2024 flags | FLAG_ALIGN, mode);
2025 if (prevToken().cat() != catAlign &&
2026 prevToken().cs() != "\\")
2031 else if (l->inset == "underset" || l->inset == "overset") {
2032 cell->push_back(createInsetMath(t.cs(), buf));
2033 parse(cell->back().nucleus()->cell(1), FLAG_ITEM, mode);
2034 parse(cell->back().nucleus()->cell(0), FLAG_ITEM, mode);
2038 MathAtom at = createInsetMath(t.cs(), buf);
2039 for (InsetMath::idx_type i = 0; i < at->nargs(); ++i)
2040 parse(at.nucleus()->cell(i),
2041 FLAG_ITEM, asMode(mode, l->extra));
2042 cell->push_back(at);
2047 bool is_unicode_symbol = false;
2048 if (mode == InsetMath::TEXT_MODE && !is_user_macro) {
2050 docstring cmd = prevToken().asInput();
2051 CatCode cat = nextToken().cat();
2052 if (cat == catBegin) {
2054 while (good() && (count || cat != catEnd)) {
2055 cat = nextToken().cat();
2056 cmd += getToken().asInput();
2058 if (cat == catBegin)
2060 else if (cat == catEnd)
2066 char_type c = Encodings::fromLaTeXCommand(cmd,
2067 Encodings::MATH_CMD | Encodings::TEXT_CMD,
2068 is_combining, termination);
2070 if (cat == catLetter)
2072 cmd += getToken().asInput();
2074 if (cat == catLetter)
2076 c = Encodings::fromLaTeXCommand(cmd,
2077 Encodings::MATH_CMD | Encodings::TEXT_CMD,
2078 is_combining, termination);
2080 if (c && buf && buf->params().encoding().encodable(c)) {
2082 if (nextToken().cat() == catBegin) {
2084 if (nextToken().cat() == catEnd) {
2089 while (nextToken().cat() == catSpace) {
2094 is_unicode_symbol = true;
2095 cell->push_back(MathAtom(new InsetMathChar(c)));
2097 while (num_tokens--)
2101 if (!is_unicode_symbol) {
2102 MathAtom at = is_user_macro ?
2103 MathAtom(new InsetMathMacro(buf, t.cs()))
2104 : createInsetMath(t.cs(), buf);
2105 InsetMath::mode_type m = mode;
2106 //if (m == InsetMath::UNDECIDED_MODE)
2107 //lyxerr << "default creation: m1: " << m << endl;
2108 if (at->currentMode() != InsetMath::UNDECIDED_MODE)
2109 m = at->currentMode();
2110 //lyxerr << "default creation: m2: " << m << endl;
2111 InsetMath::idx_type start = 0;
2112 // this fails on \bigg[...\bigg]
2114 //parse(opt, FLAG_OPTION, InsetMath::VERBATIM_MODE);
2115 //if (!opt.empty()) {
2117 // at.nucleus()->cell(0) = opt;
2119 for (InsetMath::idx_type i = start; i < at->nargs(); ++i) {
2120 parse(at.nucleus()->cell(i), FLAG_ITEM, m);
2121 if (mode == InsetMath::MATH_MODE)
2124 cell->push_back(at);
2130 if (flags & FLAG_LEAVE) {
2139 } // anonymous namespace
2142 // FIXME This will likely need some work.
2143 char const * latexkeys::MathMLtype() const
2145 if (extra == "mathord")
2151 bool mathed_parse_cell(MathData & ar, docstring const & str, Parse::flags f)
2153 return Parser(str, f, ar.buffer()).parse(ar, 0, (f & Parse::TEXTMODE) ?
2154 InsetMath::TEXT_MODE : InsetMath::MATH_MODE);
2158 bool mathed_parse_cell(MathData & ar, istream & is, Parse::flags f)
2160 return Parser(is, f, ar.buffer()).parse(ar, 0, (f & Parse::TEXTMODE) ?
2161 InsetMath::TEXT_MODE : InsetMath::MATH_MODE);
2165 bool mathed_parse_normal(Buffer * buf, MathAtom & t, docstring const & str,
2168 return Parser(str, f, buf).parse(t);
2172 bool mathed_parse_normal(Buffer * buf, MathAtom & t, Lexer & lex,
2175 return Parser(lex, f, buf).parse(t);
2179 bool mathed_parse_normal(InsetMathGrid & grid, docstring const & str,
2182 return Parser(str, f, &grid.buffer()).parse1(grid, 0, (f & Parse::TEXTMODE) ?
2183 InsetMath::TEXT_MODE : InsetMath::MATH_MODE, false);
2189 fill(theCatcode, theCatcode + 128, catOther);
2190 fill(theCatcode + 'a', theCatcode + 'z' + 1, catLetter);
2191 fill(theCatcode + 'A', theCatcode + 'Z' + 1, catLetter);
2193 theCatcode[int('\\')] = catEscape;
2194 theCatcode[int('{')] = catBegin;
2195 theCatcode[int('}')] = catEnd;
2196 theCatcode[int('$')] = catMath;
2197 theCatcode[int('&')] = catAlign;
2198 theCatcode[int('\n')] = catNewline;
2199 theCatcode[int('#')] = catParameter;
2200 theCatcode[int('^')] = catSuper;
2201 theCatcode[int('_')] = catSub;
2202 theCatcode[int(0x7f)] = catIgnore;
2203 theCatcode[int(' ')] = catSpace;
2204 theCatcode[int('\t')] = catSpace;
2205 theCatcode[int('\r')] = catNewline;
2206 theCatcode[int('~')] = catActive;
2207 theCatcode[int('%')] = catComment;