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"
76 #include "support/convert.h"
77 #include "support/debug.h"
78 #include "support/docstream.h"
79 #include "support/Lexer.h"
93 InsetMath::mode_type asMode(InsetMath::mode_type oldmode, docstring const & str)
95 //lyxerr << "handling mode: '" << str << "'" << endl;
96 if (str == "mathmode")
97 return InsetMath::MATH_MODE;
98 if (str == "textmode" || str == "forcetext")
99 return InsetMath::TEXT_MODE;
104 bool stared(docstring const & s)
106 size_t const n = s.size();
107 return n && s[n - 1] == '*';
111 docstring const repl(docstring const & oldstr, char_type const c,
112 docstring const & macro, bool textmode = false)
118 for (i = 0, j = 0; i < oldstr.size(); ++i) {
119 if (c == oldstr[i]) {
120 newstr.append(oldstr, j, i - j);
121 newstr.append(macro);
123 if (macro.size() > 2 && j < oldstr.size())
124 newstr += (textmode && oldstr[j] == ' ' ? '\\' : ' ');
132 newstr.append(oldstr, j, i - j);
137 docstring escapeSpecialChars(docstring const & str, bool textmode)
139 docstring const backslash = textmode ? from_ascii("\\textbackslash")
140 : from_ascii("\\backslash");
141 docstring const caret = textmode ? from_ascii("\\textasciicircum")
142 : from_ascii("\\mathcircumflex");
143 docstring const tilde = textmode ? from_ascii("\\textasciitilde")
144 : from_ascii("\\sim");
146 return repl(repl(repl(repl(repl(repl(repl(repl(repl(repl(str,
147 '\\', backslash, textmode),
148 '^', caret, textmode),
149 '~', tilde, textmode),
150 '_', from_ascii("\\_")),
151 '$', from_ascii("\\$")),
152 '#', from_ascii("\\#")),
153 '&', from_ascii("\\&")),
154 '%', from_ascii("\\%")),
155 '{', from_ascii("\\{")),
156 '}', from_ascii("\\}"));
161 * Add the row \p cellrow to \p grid.
162 * \returns whether the row could be added. Adding a row can fail for
163 * environments like "equation" that have a fixed number of rows.
165 bool addRow(InsetMathGrid & grid, row_type & cellrow,
166 docstring const & vskip, bool allow_newpage = true)
169 if (cellrow == grid.nrows()) {
170 //lyxerr << "adding row " << cellrow << endl;
171 grid.addRow(cellrow - 1);
172 if (cellrow == grid.nrows()) {
173 // We can't add a row to this grid, so let's
174 // append the content of this cell to the previous
176 // This does not happen in well formed .lyx files,
177 // but LyX versions 1.3.x and older could create
178 // such files and tex2lyx can still do that.
180 lyxerr << "ignoring extra row";
182 lyxerr << " with extra space " << to_utf8(vskip);
184 lyxerr << " with no page break allowed";
185 lyxerr << '.' << endl;
189 grid.vcrskip(Length(to_utf8(vskip)), cellrow - 1);
190 grid.rowinfo(cellrow - 1).allow_newpage = allow_newpage;
196 * Add the column \p cellcol to \p grid.
197 * \returns whether the column could be added. Adding a column can fail for
198 * environments like "eqnarray" that have a fixed number of columns.
200 bool addCol(InsetMathGrid & grid, col_type & cellcol)
203 if (cellcol == grid.ncols()) {
204 //lyxerr << "adding column " << cellcol << endl;
205 grid.addCol(cellcol);
206 if (cellcol == grid.ncols()) {
207 // We can't add a column to this grid, so let's
208 // append the content of this cell to the previous
210 // This does not happen in well formed .lyx files,
211 // but LyX versions 1.3.x and older could create
212 // such files and tex2lyx can still do that.
214 lyxerr << "ignoring extra column." << endl;
223 * Check whether the last row is empty and remove it if yes.
224 * Otherwise the following code
232 * will result in a grid with 3 rows (+ the dummy row that is always present),
233 * because the last '\\' opens a new row.
234 * Do never delete a row that contains a multicolumn, even if all cells empty,
235 * since the multicolumn information would get lost otherwise.
236 * Note that this is only needed for inner-hull grid types, such as array
237 * or aligned, but not for outer-hull grid types, such as eqnarray or align.
239 void delEmptyLastRow(InsetMathGrid & grid)
241 row_type const row = grid.nrows() - 1;
242 for (col_type col = 0; col < grid.ncols(); ++col) {
243 idx_type const idx = grid.index(row, col);
244 if (!grid.cell(idx).empty() ||
245 grid.cellinfo(idx).multi != InsetMathGrid::CELL_NORMAL)
248 // Copy the row information of the empty row (which would contain the
249 // last hline in the example above) to the dummy row and delete the
251 grid.rowinfo(row + 1) = grid.rowinfo(row);
257 * Tell whether the environment name corresponds to an inner-hull grid type.
259 bool innerHull(docstring const & name)
261 // For [bB]matrix, [vV]matrix, and pmatrix we can check the suffix only
262 return name == "array" || name == "cases" || name == "aligned"
263 || name == "alignedat" || name == "gathered" || name == "split"
264 || name == "subarray" || name == "tabular" || name == "matrix"
265 || name == "smallmatrix" || name.substr(1) == "matrix";
269 // These are TeX's catcodes
271 catEscape, // 0 backslash
281 catSpace, // 10 space
282 catLetter, // 11 a-zA-Z
283 catOther, // 12 none of the above
286 catInvalid // 15 <delete>
289 CatCode theCatcode[128];
292 inline CatCode catcode(char_type c)
294 /* The only characters that are not catOther lie in the pure ASCII
295 * range. Therefore theCatcode has only 128 entries.
296 * TeX itself deals with 8bit characters, so if needed this table
297 * could be enlarged to 256 entries.
298 * Any larger value does not make sense, since the fact that we use
299 * unicode internally does not change Knuth's TeX engine.
300 * Apart from that a table for the full 21bit UCS4 range would waste
301 * too much memory. */
305 return theCatcode[c];
310 FLAG_ALIGN = 1 << 0, // next & or \\ ends the parsing process
311 FLAG_BRACE_LAST = 1 << 1, // next closing brace ends the parsing
312 FLAG_RIGHT = 1 << 2, // next \\right ends the parsing process
313 FLAG_END = 1 << 3, // next \\end ends the parsing process
314 FLAG_BRACK_LAST = 1 << 4, // next closing bracket ends the parsing
315 FLAG_TEXTMODE = 1 << 5, // we are in a box
316 FLAG_ITEM = 1 << 6, // read a (possibly braced) token
317 FLAG_LEAVE = 1 << 7, // leave the loop at the end
318 FLAG_SIMPLE = 1 << 8, // next $ leaves the loop
319 FLAG_EQUATION = 1 << 9, // next \] leaves the loop
320 FLAG_SIMPLE2 = 1 << 10, // next \) leaves the loop
321 FLAG_OPTION = 1 << 11, // read [...] style option
322 FLAG_BRACED = 1 << 12 // read {...} style argument
327 // Helper class for parsing
333 Token() : cs_(), char_(0), cat_(catIgnore) {}
335 Token(char_type c, CatCode cat) : cs_(), char_(c), cat_(cat) {}
337 explicit Token(docstring const & cs) : cs_(cs), char_(0), cat_(catIgnore) {}
340 docstring const & cs() const { return cs_; }
342 CatCode cat() const { return cat_; }
344 char_type character() const { return char_; }
346 docstring asString() const { return !cs_.empty() ? cs_ : docstring(1, char_); }
348 docstring asInput() const { return !cs_.empty() ? '\\' + cs_ : docstring(1, char_); }
360 ostream & operator<<(ostream & os, Token const & t)
362 if (!t.cs().empty()) {
363 docstring const & cs = t.cs();
364 // FIXME: For some strange reason, the stream operator instantiate
365 // a new Token before outputting the contents of t.cs().
366 // Because of this the line
368 // below becomes recursive.
369 // In order to avoid that we return early:
372 os << '\\' << to_utf8(cs);
374 else if (t.cat() == catLetter)
375 os << static_cast<uint32_t>(t.character());
377 os << '[' << static_cast<uint32_t>(t.character()) << ',' << t.cat() << ']';
385 typedef InsetMath::mode_type mode_type;
387 typedef Parse::flags parse_mode;
390 Parser(Lexer & lex, parse_mode mode, Buffer * buf);
391 /// Only use this for reading from .lyx file format, for the reason
392 /// see Parser::tokenize(istream &).
393 Parser(istream & is, parse_mode mode, Buffer * buf);
395 Parser(docstring const & str, parse_mode mode, Buffer * buf);
398 bool parse(MathAtom & at);
400 bool parse(MathData & array, unsigned flags, mode_type mode);
402 bool parse1(InsetMathGrid & grid, unsigned flags, mode_type mode,
405 int lineno() const { return lineno_; }
408 /// store current position
410 /// restore previous position
412 /// forget last saved position
417 void parse2(MathAtom & at, unsigned flags, mode_type mode, bool numbered);
418 /// get arg delimited by 'left' and 'right'
419 docstring getArg(char_type left, char_type right);
423 void error(string const & msg);
424 void error(docstring const & msg) { error(to_utf8(msg)); }
425 /// dump contents to screen
427 /// Only use this for reading from .lyx file format (see
428 /// implementation for reason)
429 void tokenize(istream & is);
431 void tokenize(docstring const & s);
433 void skipSpaceTokens(idocstream & is, char_type c);
435 void push_back(Token const & t);
437 Token const & prevToken() const;
439 Token const & nextToken() const;
441 Token const & getToken();
442 /// skips spaces if any
445 void lex(docstring const & s);
449 docstring parse_verbatim_item();
451 docstring parse_verbatim_option();
456 vector<Token> tokens_;
460 std::vector<unsigned> positions_;
461 /// Stack of active environments
462 vector<docstring> environments_;
472 Parser::Parser(Lexer & lexer, parse_mode mode, Buffer * buf)
473 : lineno_(lexer.lineNumber()), pos_(0), mode_(mode), success_(true),
476 tokenize(lexer.getStream());
481 Parser::Parser(istream & is, parse_mode mode, Buffer * buf)
482 : lineno_(0), pos_(0), mode_(mode), success_(true), buffer_(buf)
488 Parser::Parser(docstring const & str, parse_mode mode, Buffer * buf)
489 : lineno_(0), pos_(0), mode_(mode), success_(true), buffer_(buf)
495 void Parser::push_back(Token const & t)
497 tokens_.push_back(t);
501 Token const & Parser::prevToken() const
503 static const Token dummy;
504 return pos_ > 0 ? tokens_[pos_ - 1] : dummy;
508 Token const & Parser::nextToken() const
510 static const Token dummy;
511 return good() ? tokens_[pos_] : dummy;
515 Token const & Parser::getToken()
517 static const Token dummy;
518 //lyxerr << "looking at token " << tokens_[pos_] << " pos: " << pos_ << endl;
519 return good() ? tokens_[pos_++] : dummy;
523 void Parser::skipSpaces()
525 while (nextToken().cat() == catSpace || nextToken().cat() == catNewline)
530 void Parser::putback()
536 void Parser::pushPosition()
538 positions_.push_back(pos_);
542 void Parser::popPosition()
544 pos_ = positions_.back();
545 positions_.pop_back();
549 void Parser::dropPosition()
551 positions_.pop_back();
555 bool Parser::good() const
557 return pos_ < tokens_.size();
561 char_type Parser::getChar()
564 error("The input stream is not well...");
567 return tokens_[pos_++].character();
571 docstring Parser::getArg(char_type left, char_type right)
579 char_type c = getChar();
584 while ((c = getChar()) != right && good())
591 void Parser::skipSpaceTokens(idocstream & is, char_type c)
593 // skip trailing spaces
594 while (catcode(c) == catSpace || catcode(c) == catNewline)
597 //lyxerr << "putting back: " << c << endl;
602 void Parser::tokenize(istream & is)
604 // eat everything up to the next \end_inset or end of stream
605 // and store it in s for further tokenization
610 if (s.size() >= 10 && s.substr(s.size() - 10) == "\\end_inset") {
611 s = s.substr(0, s.size() - 10);
615 // Remove the space after \end_inset
616 if (is.get(c) && c != ' ')
620 tokenize(from_utf8(s));
624 void Parser::tokenize(docstring const & buffer)
626 idocstringstream is((mode_ & Parse::VERBATIM)
627 ? escapeSpecialChars(buffer, mode_ & Parse::TEXTMODE)
628 : buffer, ios::in | ios::binary);
632 //lyxerr << "reading c: " << c << endl;
634 switch (catcode(c)) {
638 if (catcode(c) == catNewline)
639 ; //push_back(Token("par"));
641 push_back(Token('\n', catNewline));
649 while (is.get(c) && catcode(c) != catNewline)
659 error("unexpected end of input");
664 if (catcode(c) == catLetter) {
666 while (is.get(c) && catcode(c) == catLetter)
668 skipSpaceTokens(is, c);
677 push_back(Token(c, catcode(c)));
679 skipSpaceTokens(is, c);
684 if (!(mode_ & Parse::QUIET))
685 lyxerr << "ignoring a char: " << int(c) << endl;
690 push_back(Token(c, catcode(c)));
700 void Parser::dump() const
702 lyxerr << "\nTokens: ";
703 for (unsigned i = 0; i < tokens_.size(); ++i) {
706 lyxerr << tokens_[i];
708 lyxerr << " pos: " << pos_ << endl;
712 void Parser::error(string const & msg)
715 if (!(mode_ & Parse::QUIET)) {
716 lyxerr << "Line ~" << lineno_ << ": Math parse error: "
723 bool Parser::parse(MathAtom & at)
726 MathData ar(buffer_);
727 parse(ar, false, InsetMath::UNDECIDED_MODE);
728 if (ar.size() != 1 || ar.front()->getType() == hullNone) {
729 if (!(mode_ & Parse::QUIET))
730 lyxerr << "unusual contents found: " << ar << endl;
731 at = MathAtom(new InsetMathPar(buffer_, ar));
732 //if (at->nargs() > 0)
733 // at.nucleus()->cell(0) = ar(buffer_);
735 // lyxerr << "unusual contents found: " << ar << endl;
743 docstring Parser::parse_verbatim_option()
747 if (nextToken().character() == '[') {
750 for (Token t = getToken(); t.character() != ']' && good(); t = getToken()) {
751 if (t.cat() == catBegin) {
753 res += '{' + parse_verbatim_item() + '}';
762 docstring Parser::parse_verbatim_item()
766 if (nextToken().cat() == catBegin) {
769 for (Token t = getToken(); t.cat() != catEnd && good(); t = getToken()) {
770 if (t.cat() == catBegin) {
772 res += '{' + parse_verbatim_item() + '}';
782 bool Parser::parse(MathData & array, unsigned flags, mode_type mode)
784 InsetMathGrid grid(buffer_, 1, 1);
785 parse1(grid, flags, mode, false);
786 array = grid.cell(0);
791 void Parser::parse2(MathAtom & at, const unsigned flags, const mode_type mode,
794 parse1(*(at.nucleus()->asGridInset()), flags, mode, numbered);
798 bool Parser::parse1(InsetMathGrid & grid, unsigned flags,
799 const mode_type mode, const bool numbered)
801 row_type cellrow = 0;
802 col_type cellcol = 0;
803 MathData * cell = &grid.cell(grid.index(cellrow, cellcol));
804 Buffer * buf = buffer_;
806 if (grid.asHullInset())
807 grid.asHullInset()->numbered(cellrow, numbered);
810 //lyxerr << " flags: " << flags << endl;
811 //lyxerr << " mode: " << mode << endl;
812 //lyxerr << "grid: " << grid << endl;
815 Token const & t = getToken();
818 lyxerr << "t: " << t << " flags: " << flags << endl;
819 lyxerr << "mode: " << mode << endl;
824 if (flags & FLAG_ITEM) {
826 if (t.cat() == catBegin) {
827 // skip the brace and collect everything to the next matching
829 parse1(grid, FLAG_BRACE_LAST, mode, numbered);
833 // handle only this single token, leave the loop if done
838 if (flags & FLAG_BRACED) {
839 if (t.cat() == catSpace)
842 if (t.cat() != catBegin) {
843 error("opening brace expected");
847 // skip the brace and collect everything to the next matching
849 flags = FLAG_BRACE_LAST;
853 if (flags & FLAG_OPTION) {
854 if (t.cat() == catOther && t.character() == '[') {
856 parse(ar, FLAG_BRACK_LAST, mode);
859 // no option found, put back token and we are done
868 if (t.cat() == catMath) {
869 if (mode != InsetMath::MATH_MODE) {
870 // we are inside some text mode thingy, so opening new math is allowed
871 Token const & n = getToken();
872 if (n.cat() == catMath) {
873 // TeX's $$...$$ syntax for displayed math
874 if (mode == InsetMath::UNDECIDED_MODE) {
875 cell->push_back(MathAtom(new InsetMathHull(buf, hullEquation)));
876 parse2(cell->back(), FLAG_SIMPLE, InsetMath::MATH_MODE, false);
877 getToken(); // skip the second '$' token
879 // This is not an outer hull and display math is
880 // not allowed inside text mode environments.
881 error("bad math environment $$");
885 // simple $...$ stuff
887 if (mode == InsetMath::UNDECIDED_MODE) {
888 cell->push_back(MathAtom(new InsetMathHull(buf, hullSimple)));
889 parse2(cell->back(), FLAG_SIMPLE, InsetMath::MATH_MODE, false);
891 // Don't create nested math hulls (bug #5392)
892 cell->push_back(MathAtom(new InsetMathEnsureMath(buf)));
893 parse(cell->back().nucleus()->cell(0), FLAG_SIMPLE, InsetMath::MATH_MODE);
898 else if (flags & FLAG_SIMPLE) {
899 // this is the end of the formula
904 Token const & n = getToken();
905 if (n.cat() == catMath) {
906 error("something strange in the parser");
909 // This is inline math ($...$), but the parser thinks we are
910 // already in math mode and latex would issue an error, unless we
911 // are inside a text mode user macro. We have no way to tell, so
912 // let's play safe by using \ensuremath, as it will work in any case.
914 cell->push_back(MathAtom(new InsetMathEnsureMath(buf)));
915 parse(cell->back().nucleus()->cell(0), FLAG_SIMPLE, InsetMath::MATH_MODE);
920 else if (t.cat() == catLetter)
921 cell->push_back(MathAtom(new InsetMathChar(buf, t.character())));
923 else if (t.cat() == catSpace && mode != InsetMath::MATH_MODE) {
924 if (cell->empty() || cell->back()->getChar() != ' ')
925 cell->push_back(MathAtom(new InsetMathChar(buf, t.character())));
928 else if (t.cat() == catNewline && mode != InsetMath::MATH_MODE) {
929 if (cell->empty() || cell->back()->getChar() != ' ')
930 cell->push_back(MathAtom(new InsetMathChar(buf, ' ')));
933 else if (t.cat() == catParameter) {
934 Token const & n = nextToken();
935 char_type c = n.character();
936 if (c && '0' < c && c <= '9') {
937 cell->push_back(MathAtom(new InsetMathMacroArgument(buf, c - '0')));
940 cell->push_back(MathAtom(new InsetMathHash(buf)));
943 else if (t.cat() == catActive)
944 cell->push_back(MathAtom(new InsetMathSpace(buf, string(1, t.character()), "")));
946 else if (t.cat() == catBegin) {
948 parse(ar, FLAG_BRACE_LAST, mode);
949 // do not create a BraceInset if they were written by LyX
950 // this helps to keep the annoyance of "a choose b" to a minimum
951 if (ar.size() == 1 && ar[0]->extraBraces())
954 cell->push_back(MathAtom(new InsetMathBrace(buf, ar)));
957 else if (t.cat() == catEnd) {
958 if (flags & FLAG_BRACE_LAST)
960 error("found '}' unexpectedly");
961 //LASSERT(false, /**/);
962 //add(cell, '}', LM_TC_TEX);
965 else if (t.cat() == catAlign) {
966 //lyxerr << " column now " << (cellcol + 1)
967 // << " max: " << grid.ncols() << endl;
968 if (flags & FLAG_ALIGN)
970 if (addCol(grid, cellcol))
971 cell = &grid.cell(grid.index(cellrow, cellcol));
974 else if (t.cat() == catSuper || t.cat() == catSub) {
975 bool up = (t.cat() == catSuper);
976 // we need no new script inset if the last thing was a scriptinset,
977 // which has that script already not the same script already
979 cell->push_back(MathAtom(new InsetMathScript(buf, up)));
980 else if (cell->back()->asScriptInset() &&
981 !cell->back()->asScriptInset()->has(up))
982 cell->back().nucleus()->asScriptInset()->ensure(up);
983 else if (cell->back()->asScriptInset())
984 cell->push_back(MathAtom(new InsetMathScript(buf, up)));
986 cell->back() = MathAtom(new InsetMathScript(buf, cell->back(), up));
987 InsetMathScript * p = cell->back().nucleus()->asScriptInset();
988 // special handling of {}-bases
989 // Here we could remove the brace inset for things
990 // like {a'}^2 and add the braces back in
991 // InsetMathScript::write().
992 // We do not do it, since it is not possible to detect
993 // reliably whether the braces are needed because the
994 // nucleus contains more than one symbol, or whether
995 // they are needed for unknown commands like \xx{a}_0
996 // or \yy{a}{b}_0. This was done in revision 14819
997 // in an unreliable way. See this thread
998 // http://www.mail-archive.com/lyx-devel%40lists.lyx.org/msg104917.html
1000 // However, we remove empty braces because they look
1001 // ugly on screen and we are sure that they were added
1002 // by the write() method (and will be re-added on save).
1003 if (p->nuc().size() == 1 &&
1004 p->nuc().back()->asBraceInset() &&
1005 p->nuc().back()->asBraceInset()->cell(0).empty())
1008 parse(p->cell(p->idxOfScript(up)), FLAG_ITEM, mode);
1011 else if (t.character() == ']' && (flags & FLAG_BRACK_LAST)) {
1012 //lyxerr << "finished reading option" << endl;
1016 else if (t.cat() == catOther) {
1017 char_type c = t.character();
1018 if (!Encodings::isUnicodeTextOnly(c)
1019 || mode_ & Parse::VERBATIM
1020 || !(mode_ & Parse::USETEXT)
1021 || mode == InsetMath::TEXT_MODE) {
1022 cell->push_back(MathAtom(new InsetMathChar(buf, c)));
1024 MathAtom at = createInsetMath("text", buf);
1025 at.nucleus()->cell(0).push_back(MathAtom(new InsetMathChar(buf, c)));
1026 while (nextToken().cat() == catOther
1027 && Encodings::isUnicodeTextOnly(nextToken().character())) {
1028 c = getToken().character();
1029 at.nucleus()->cell(0).push_back(MathAtom(new InsetMathChar(buf, c)));
1031 cell->push_back(at);
1035 else if (t.cat() == catComment) {
1038 Token const & tt = getToken();
1039 if (tt.cat() == catNewline)
1043 cell->push_back(MathAtom(new InsetMathComment(buf, s)));
1048 // control sequences
1051 else if (t.cs() == "lyxlock") {
1053 cell->back().nucleus()->lock(true);
1056 else if ((t.cs() == "global" && nextToken().cs() == "def") ||
1058 if (t.cs() == "global")
1062 docstring name = getToken().cs();
1067 while (good() && nextToken().cat() != catBegin) {
1068 pars += getToken().cs();
1075 parse(def, FLAG_ITEM, InsetMath::UNDECIDED_MODE);
1077 // is a version for display attached?
1079 MathData display(buf);
1080 if (nextToken().cat() == catBegin)
1081 parse(display, FLAG_ITEM, InsetMath::MATH_MODE);
1083 cell->push_back(MathAtom(new InsetMathMacroTemplate(buf,
1084 name, nargs, 0, MacroTypeDef,
1085 vector<MathData>(), def, display)));
1087 if (buf && (mode_ & Parse::TRACKMACRO))
1088 buf->usermacros.insert(name);
1091 else if (t.cs() == "newcommand" ||
1092 t.cs() == "renewcommand" ||
1093 t.cs() == "newlyxcommand") {
1095 if (getToken().cat() != catBegin) {
1096 error("'{' in \\newcommand expected (1) ");
1099 docstring name = getToken().cs();
1100 if (getToken().cat() != catEnd) {
1101 error("'}' in \\newcommand expected");
1106 docstring const arg = getArg('[', ']');
1109 nargs = convert<int>(arg);
1111 // optional argument given?
1114 vector<MathData> optionalValues;
1115 while (nextToken().character() == '[') {
1117 optionalValues.push_back(MathData(buf));
1118 parse(optionalValues[optionals], FLAG_BRACK_LAST, mode);
1123 parse(def, FLAG_ITEM, InsetMath::UNDECIDED_MODE);
1125 // is a version for display attached?
1127 MathData display(buf);
1128 if (nextToken().cat() == catBegin)
1129 parse(display, FLAG_ITEM, InsetMath::MATH_MODE);
1131 cell->push_back(MathAtom(new InsetMathMacroTemplate(buf,
1132 name, nargs, optionals, MacroTypeNewcommand,
1133 optionalValues, def, display)));
1135 if (buf && (mode_ & Parse::TRACKMACRO))
1136 buf->usermacros.insert(name);
1139 else if (t.cs() == "newcommandx" ||
1140 t.cs() == "renewcommandx") {
1141 // \newcommandx{\foo}[2][usedefault, addprefix=\global,1=default]{#1,#2}
1144 if (nextToken().cat() == catBegin) {
1146 name = getToken().cs();
1147 if (getToken().cat() != catEnd) {
1148 error("'}' in \\newcommandx expected");
1152 name = getToken().cs();
1155 docstring const arg = getArg('[', ']');
1157 error("[num] in \\newcommandx expected");
1160 int nargs = convert<int>(arg);
1164 vector<MathData> optionalValues;
1165 if (nextToken().character() == '[') {
1169 // handle 'opt=value' options, separated by ','.
1171 while (nextToken().character() != ']' && good()) {
1172 if (nextToken().character() >= '1'
1173 && nextToken().character() <= '9') {
1174 // optional value -> get parameter number
1175 int n = getChar() - '0';
1177 error("Arity of \\newcommandx too low "
1178 "for given optional parameter.");
1183 if (getToken().character() != '=') {
1184 error("'=' and optional parameter value "
1185 "expected for \\newcommandx");
1190 int optNum = max(size_t(n), optionalValues.size());
1191 optionalValues.resize(optNum, MathData(buf));
1192 optionalValues[n - 1].clear();
1193 while (nextToken().character() != ']'
1194 && nextToken().character() != ',') {
1196 parse(data, FLAG_ITEM, InsetMath::UNDECIDED_MODE);
1197 optionalValues[n - 1].append(data);
1199 optionals = max(n, optionals);
1200 } else if (nextToken().cat() == catLetter) {
1201 // we in fact ignore every non-optional
1206 while (nextToken().cat() == catLetter)
1211 MathData value(buf);
1212 if (nextToken().character() == '=') {
1214 while (nextToken().character() != ']'
1215 && nextToken().character() != ',')
1216 parse(value, FLAG_ITEM,
1217 InsetMath::UNDECIDED_MODE);
1220 error("option for \\newcommandx expected");
1226 if (nextToken().character() == ',') {
1229 } else if (nextToken().character() != ']') {
1230 error("Expecting ',' or ']' in options "
1231 "of \\newcommandx");
1244 parse(def, FLAG_ITEM, InsetMath::UNDECIDED_MODE);
1246 // is a version for display attached?
1248 MathData display(buf);
1249 if (nextToken().cat() == catBegin)
1250 parse(display, FLAG_ITEM, InsetMath::MATH_MODE);
1252 cell->push_back(MathAtom(new InsetMathMacroTemplate(buf,
1253 name, nargs, optionals, MacroTypeNewcommandx,
1254 optionalValues, def, display)));
1256 if (buf && (mode_ & Parse::TRACKMACRO))
1257 buf->usermacros.insert(name);
1260 else if (t.cs() == "(") {
1261 if (mode == InsetMath::UNDECIDED_MODE) {
1262 cell->push_back(MathAtom(new InsetMathHull(buf, hullSimple)));
1263 parse2(cell->back(), FLAG_SIMPLE2, InsetMath::MATH_MODE, false);
1265 // Don't create nested math hulls (bug #5392)
1266 cell->push_back(MathAtom(new InsetMathEnsureMath(buf)));
1267 parse(cell->back().nucleus()->cell(0), FLAG_SIMPLE2, InsetMath::MATH_MODE);
1271 else if (t.cs() == "[") {
1272 if (mode != InsetMath::UNDECIDED_MODE) {
1273 error("bad math environment [");
1276 cell->push_back(MathAtom(new InsetMathHull(buf, hullEquation)));
1277 parse2(cell->back(), FLAG_EQUATION, InsetMath::MATH_MODE, false);
1280 else if (t.cs() == "protect")
1281 // ignore \\protect, will hopefully be re-added during output
1284 else if (t.cs() == "end") {
1285 if (flags & FLAG_END) {
1286 // eat environment name
1287 docstring const name = getArg('{', '}');
1288 if (environments_.empty())
1289 error("'found \\end{" + name +
1290 "}' without matching '\\begin{" +
1292 else if (name != environments_.back())
1293 error("'\\end{" + name +
1294 "}' does not match '\\begin{" +
1295 environments_.back() + "}'");
1297 environments_.pop_back();
1298 // Delete empty last row in matrix
1300 // If you abuse InsetMathGrid for
1301 // non-matrix like structures you
1302 // probably need to refine this test.
1303 // Right now we only have to test for
1304 // single line hull insets.
1305 if (grid.nrows() > 1 && innerHull(name))
1306 delEmptyLastRow(grid);
1310 error("found 'end' unexpectedly");
1313 else if (t.cs() == ")") {
1314 if (flags & FLAG_SIMPLE2)
1316 error("found '\\)' unexpectedly");
1319 else if (t.cs() == "]") {
1320 if (flags & FLAG_EQUATION)
1322 error("found '\\]' unexpectedly");
1325 else if (t.cs() == "\\") {
1326 if (flags & FLAG_ALIGN)
1328 bool starred = false;
1330 if (nextToken().asInput() == "*") {
1333 } else if (nextToken().asInput() == "[")
1334 arg = getArg('[', ']');
1336 error("missing token after \\\\");
1337 // skip "{}" added in front of "[" (the
1338 // counterpart is in InsetMathGrid::eolString())
1339 // skip spaces because formula could come from tex2lyx
1340 bool skipBraces = false;
1342 if (nextToken().cat() == catBegin) {
1344 if (nextToken().cat() == catEnd) {
1348 if (nextToken().asInput() == "[")
1357 bool const added = addRow(grid, cellrow, arg, !starred);
1360 if (grid.asHullInset())
1361 grid.asHullInset()->numbered(
1363 cell = &grid.cell(grid.index(cellrow,
1368 else if (t.cs() == "multicolumn" && grid.handlesMulticolumn()) {
1369 // if the columns are specified numerically,
1370 // extract column count and insert dummy cells,
1371 // otherwise parse it as an user macro
1372 MathData count(buf);
1373 parse(count, FLAG_ITEM, mode);
1375 // limit arbitrarily to 100 columns
1376 if (extractNumber(count, cols) && cols > 0 && cols < 100) {
1377 // resize the table if necessary
1378 size_t first = grid.index(cellrow, cellcol);
1379 for (int i = 1; i < cols; ++i) {
1380 if (addCol(grid, cellcol)) {
1381 size_t const idx = grid.index(cellrow, cellcol);
1382 grid.cellinfo(idx).multi =
1383 InsetMathGrid::CELL_PART_OF_MULTICOLUMN;
1387 // the first cell is the real thing, not a dummy
1388 cell = &grid.cell(first);
1389 grid.cellinfo(first).multi =
1390 InsetMathGrid::CELL_BEGIN_OF_MULTICOLUMN;
1392 // read special alignment
1393 MathData align(buf);
1394 parse(align, FLAG_ITEM, mode);
1395 grid.cellinfo(first).align = asString(align);
1397 // parse the remaining contents into the "real" cell
1398 parse(*cell, FLAG_ITEM, mode);
1400 MathAtom at = MathAtom(new InsetMathMacro(buf, t.cs()));
1401 cell->push_back(at);
1402 cell->push_back(MathAtom(new InsetMathBrace(buf, count)));
1406 else if (t.cs() == "limits" || t.cs() == "nolimits") {
1408 cell->back()->limits(t.cs() == "limits" ? LIMITS : NO_LIMITS);
1410 MathAtom at = createInsetMath(t.cs(), buf);
1411 cell->push_back(at);
1415 // \notag is the same as \nonumber if amsmath is used
1416 else if ((t.cs() == "nonumber" || t.cs() == "notag") &&
1418 grid.asHullInset()->numbered(cellrow, false);
1420 else if (t.cs() == "number" && grid.asHullInset())
1421 grid.asHullInset()->numbered(cellrow, true);
1423 else if (t.cs() == "hline") {
1424 grid.rowinfo(cellrow).lines++;
1427 else if (t.cs() == "sqrt") {
1429 parse(ar, FLAG_OPTION, mode);
1431 cell->push_back(MathAtom(new InsetMathRoot(buf)));
1432 cell->back().nucleus()->cell(1) = ar;
1434 cell->push_back(MathAtom(new InsetMathSqrt(buf)));
1435 parse(cell->back().nucleus()->cell(0), FLAG_ITEM, mode);
1438 else if (t.cs() == "cancelto") {
1440 parse(ar, FLAG_ITEM, mode);
1441 cell->push_back(MathAtom(new InsetMathCancelto(buf)));
1442 cell->back().nucleus()->cell(1) = ar;
1443 parse(cell->back().nucleus()->cell(0), FLAG_ITEM, mode);
1446 else if (t.cs() == "unit") {
1447 // Allowed formats \unit[val]{unit}
1449 parse(ar, FLAG_OPTION, mode);
1451 cell->push_back(MathAtom(new InsetMathFrac(buf, InsetMathFrac::UNIT)));
1452 cell->back().nucleus()->cell(0) = ar;
1453 parse(cell->back().nucleus()->cell(1), FLAG_ITEM, mode);
1455 cell->push_back(MathAtom(new InsetMathFrac(buf, InsetMathFrac::UNIT, 1)));
1456 parse(cell->back().nucleus()->cell(0), FLAG_ITEM, mode);
1460 else if (t.cs() == "unitfrac") {
1461 // Here allowed formats are \unitfrac[val]{num}{denom}
1463 parse(ar, FLAG_OPTION, mode);
1465 cell->push_back(MathAtom(new InsetMathFrac(buf, InsetMathFrac::UNITFRAC, 3)));
1466 cell->back().nucleus()->cell(2) = ar;
1468 cell->push_back(MathAtom(new InsetMathFrac(buf, InsetMathFrac::UNITFRAC)));
1470 parse(cell->back().nucleus()->cell(0), FLAG_ITEM, mode);
1471 parse(cell->back().nucleus()->cell(1), FLAG_ITEM, mode);
1474 else if (t.cs() == "cfrac") {
1475 // allowed formats are \cfrac[pos]{num}{denom}
1476 docstring const arg = getArg('[', ']');
1477 //lyxerr << "got so far: '" << arg << "'" << endl;
1479 cell->push_back(MathAtom(new InsetMathFrac(buf, InsetMathFrac::CFRACLEFT)));
1480 else if (arg == "r")
1481 cell->push_back(MathAtom(new InsetMathFrac(buf, InsetMathFrac::CFRACRIGHT)));
1482 else if (arg.empty() || arg == "c")
1483 cell->push_back(MathAtom(new InsetMathFrac(buf, InsetMathFrac::CFRAC)));
1485 error("found invalid optional argument");
1488 parse(cell->back().nucleus()->cell(0), FLAG_ITEM, mode);
1489 parse(cell->back().nucleus()->cell(1), FLAG_ITEM, mode);
1492 else if (t.cs() == "sideset") {
1493 // Here allowed formats are \sideset{_{bl}^{tl}}{_{br}^{tr}}{operator}
1494 MathData ar[2]= { MathData(buf), MathData(buf) };
1495 InsetMathScript * script[2] = {0, 0};
1496 for (int i = 0; i < 2; ++i) {
1497 parse(ar[i], FLAG_ITEM, mode);
1498 if (ar[i].size() == 1)
1499 script[i] = ar[i][0].nucleus()->asScriptInset();
1501 bool const hasscript[2] = {script[0] != nullptr, script[1] != nullptr};
1502 cell->push_back(MathAtom(new InsetMathSideset(buf, hasscript[0], hasscript[1])));
1504 if (script[0]->hasDown())
1505 cell->back().nucleus()->cell(1) = script[0]->down();
1506 if (script[0]->hasUp())
1507 cell->back().nucleus()->cell(2) = script[0]->up();
1509 cell->back().nucleus()->cell(1) = ar[0];
1511 if (script[1]->hasDown())
1512 cell->back().nucleus()->cell(2 + hasscript[0]) = script[1]->down();
1513 if (script[1]->hasUp())
1514 cell->back().nucleus()->cell(3 + hasscript[0]) = script[1]->up();
1516 cell->back().nucleus()->cell(2 + hasscript[0]) = ar[1];
1517 parse(cell->back().nucleus()->cell(0), FLAG_ITEM, mode);
1520 else if (t.cs() == "stackrel") {
1521 // Here allowed formats are \stackrel[subscript]{superscript}{operator}
1523 parse(ar, FLAG_OPTION, mode);
1524 cell->push_back(MathAtom(new InsetMathStackrel(buf, !ar.empty())));
1526 cell->back().nucleus()->cell(2) = ar;
1527 parse(cell->back().nucleus()->cell(1), FLAG_ITEM, mode);
1528 parse(cell->back().nucleus()->cell(0), FLAG_ITEM, mode);
1531 else if (t.cs() == "xrightarrow" || t.cs() == "xleftarrow") {
1532 cell->push_back(createInsetMath(t.cs(), buf));
1533 parse(cell->back().nucleus()->cell(1), FLAG_OPTION, mode);
1534 parse(cell->back().nucleus()->cell(0), FLAG_ITEM, mode);
1537 else if (t.cs() == "xhookrightarrow" || t.cs() == "xhookleftarrow" ||
1538 t.cs() == "xRightarrow" || t.cs() == "xLeftarrow" ||
1539 t.cs() == "xleftrightarrow" || t.cs() == "xLeftrightarrow" ||
1540 t.cs() == "xrightharpoondown" || t.cs() == "xrightharpoonup" ||
1541 t.cs() == "xleftharpoondown" || t.cs() == "xleftharpoonup" ||
1542 t.cs() == "xleftrightharpoons" || t.cs() == "xrightleftharpoons" ||
1543 t.cs() == "xmapsto") {
1544 cell->push_back(createInsetMath(t.cs(), buf));
1545 parse(cell->back().nucleus()->cell(1), FLAG_OPTION, mode);
1546 parse(cell->back().nucleus()->cell(0), FLAG_ITEM, mode);
1549 else if (t.cs() == "ref" || t.cs() == "eqref" || t.cs() == "prettyref"
1550 || t.cs() == "nameref" || t.cs() == "pageref"
1551 || t.cs() == "vpageref" || t.cs() == "vref"
1552 || t.cs() == "formatted" || t.cs() == "labelonly") {
1553 cell->push_back(MathAtom(new InsetMathRef(buf, t.cs())));
1554 docstring const opt = parse_verbatim_option();
1555 docstring const ref = parse_verbatim_item();
1557 cell->back().nucleus()->cell(1).push_back(
1558 MathAtom(new InsetMathString(buf, opt)));
1560 cell->back().nucleus()->cell(0).push_back(
1561 MathAtom(new InsetMathString(buf, ref)));
1564 else if (t.cs() == "left") {
1566 Token const & tl = getToken();
1567 // \| and \Vert are equivalent, and InsetMathDelim
1569 // FIXME: fix this in InsetMathDelim itself!
1570 docstring const l = tl.cs() == "|" ? from_ascii("Vert") : tl.asString();
1572 parse(ar, FLAG_RIGHT, mode);
1576 Token const & tr = getToken();
1577 docstring const r = tr.cs() == "|" ? from_ascii("Vert") : tr.asString();
1578 cell->push_back(MathAtom(new InsetMathDelim(buf, l, r, ar)));
1581 else if (t.cs() == "right") {
1582 if (flags & FLAG_RIGHT)
1584 //lyxerr << "got so far: '" << cell << "'" << endl;
1585 error("Unmatched right delimiter");
1589 else if (t.cs() == "begin") {
1590 docstring const name = getArg('{', '}');
1594 error("found invalid environment");
1598 environments_.push_back(name);
1600 if (name == "array" || name == "subarray") {
1601 docstring const valign = parse_verbatim_option() + 'c';
1602 docstring const halign = parse_verbatim_item();
1603 cell->push_back(MathAtom(new InsetMathArray(buf, name,
1604 InsetMathGrid::guessColumns(halign), 1, (char)valign[0], halign)));
1605 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, false);
1608 else if (name == "tabular") {
1609 docstring const valign = parse_verbatim_option() + 'c';
1610 docstring const halign = parse_verbatim_item();
1611 cell->push_back(MathAtom(new InsetMathTabular(buf, name,
1612 InsetMathGrid::guessColumns(halign), 1, (char)valign[0], halign)));
1613 parse2(cell->back(), FLAG_END, InsetMath::TEXT_MODE, false);
1616 else if (name == "split" || name == "cases") {
1617 cell->push_back(createInsetMath(name, buf));
1618 parse2(cell->back(), FLAG_END, mode, false);
1621 else if (name == "alignedat") {
1622 docstring const valign = parse_verbatim_option() + 'c';
1623 // ignore this for a while
1625 cell->push_back(MathAtom(new InsetMathSplit(buf, name, (char)valign[0])));
1626 parse2(cell->back(), FLAG_END, mode, false);
1629 else if (name == "math") {
1630 if (mode == InsetMath::UNDECIDED_MODE) {
1631 cell->push_back(MathAtom(new InsetMathHull(buf, hullSimple)));
1632 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, false);
1634 // Don't create nested math hulls (bug #5392)
1635 cell->push_back(MathAtom(new InsetMathEnsureMath(buf)));
1636 parse(cell->back().nucleus()->cell(0), FLAG_END, InsetMath::MATH_MODE);
1640 else if (name == "equation" || name == "equation*"
1641 || name == "displaymath") {
1642 if (mode != InsetMath::UNDECIDED_MODE) {
1643 error("bad math environment " + name);
1646 cell->push_back(MathAtom(new InsetMathHull(buf, hullEquation)));
1647 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, (name == "equation"));
1650 else if (name == "eqnarray" || name == "eqnarray*") {
1651 if (mode != InsetMath::UNDECIDED_MODE) {
1652 error("bad math environment " + name);
1655 cell->push_back(MathAtom(new InsetMathHull(buf, hullEqnArray)));
1656 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, !stared(name));
1659 else if (name == "align" || name == "align*") {
1660 if (mode == InsetMath::UNDECIDED_MODE) {
1661 cell->push_back(MathAtom(new InsetMathHull(buf, hullAlign)));
1662 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, !stared(name));
1664 cell->push_back(MathAtom(new InsetMathSplit(buf, name,
1665 'c', !stared(name))));
1666 parse2(cell->back(), FLAG_END, mode, !stared(name));
1670 else if (name == "flalign" || name == "flalign*") {
1671 if (mode != InsetMath::UNDECIDED_MODE) {
1672 error("bad math environment " + name);
1675 cell->push_back(MathAtom(new InsetMathHull(buf, hullFlAlign)));
1676 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, !stared(name));
1679 else if (name == "alignat" || name == "alignat*") {
1680 if (mode != InsetMath::UNDECIDED_MODE) {
1681 error("bad math environment " + name);
1684 // ignore this for a while
1686 cell->push_back(MathAtom(new InsetMathHull(buf, hullAlignAt)));
1687 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, !stared(name));
1690 else if (name == "xalignat" || name == "xalignat*") {
1691 if (mode != InsetMath::UNDECIDED_MODE) {
1692 error("bad math environment " + name);
1695 // ignore this for a while
1697 cell->push_back(MathAtom(new InsetMathHull(buf, hullXAlignAt)));
1698 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, !stared(name));
1701 else if (name == "xxalignat") {
1702 if (mode != InsetMath::UNDECIDED_MODE) {
1703 error("bad math environment " + name);
1706 // ignore this for a while
1708 cell->push_back(MathAtom(new InsetMathHull(buf, hullXXAlignAt)));
1709 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, !stared(name));
1712 else if (name == "multline" || name == "multline*") {
1713 if (mode != InsetMath::UNDECIDED_MODE) {
1714 error("bad math environment " + name);
1717 cell->push_back(MathAtom(new InsetMathHull(buf, hullMultline)));
1718 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, !stared(name));
1721 else if (name == "gather" || name == "gather*") {
1722 if (mode != InsetMath::UNDECIDED_MODE) {
1723 error("bad math environment " + name);
1726 cell->push_back(MathAtom(new InsetMathHull(buf, hullGather)));
1727 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, !stared(name));
1730 else if (latexkeys const * l = in_word_set(name)) {
1731 if (l->inset == "matrix") {
1732 cell->push_back(createInsetMath(name, buf));
1733 parse2(cell->back(), FLAG_END, mode, false);
1734 } else if (l->inset == "split") {
1735 docstring const valign = parse_verbatim_option() + 'c';
1736 cell->push_back(MathAtom(
1737 new InsetMathSplit(buf, name, (char)valign[0])));
1738 parse2(cell->back(), FLAG_END, mode, false);
1741 if (!(mode_ & Parse::QUIET)) {
1743 lyxerr << "found math environment `"
1745 << "' in symbols file with unsupported inset `"
1749 // create generic environment inset
1750 cell->push_back(MathAtom(new InsetMathEnv(buf, name)));
1751 parse(cell->back().nucleus()->cell(0), FLAG_END, mode);
1757 if (!(mode_ & Parse::QUIET) &&
1758 !(mode_ & Parse::TRACKMACRO)) {
1760 lyxerr << "found unknown math environment '"
1761 << to_utf8(name) << "'" << endl;
1763 // create generic environment inset
1764 cell->push_back(MathAtom(new InsetMathEnv(buf, name)));
1765 parse(cell->back().nucleus()->cell(0), FLAG_END, mode);
1769 else if (t.cs() == "kern" || t.cs() == "mkern") {
1774 Token const & tt = getToken();
1778 while (num_tokens--)
1782 s += tt.character();
1783 if (isValidLength(to_utf8(s)))
1787 cell->push_back(MathAtom(new InsetMathMacro(buf, t.cs())));
1789 cell->push_back(MathAtom(new InsetMathKern(buf, s)));
1792 else if (t.cs() == "label") {
1793 // FIXME: This is swallowed in inline formulas
1794 docstring label = parse_verbatim_item();
1797 if (grid.asHullInset()) {
1798 grid.asHullInset()->label(cellrow, label);
1800 cell->push_back(createInsetMath(t.cs(), buf));
1801 cell->push_back(MathAtom(new InsetMathBrace(buf, ar)));
1805 else if (t.cs() == "choose" || t.cs() == "over"
1806 || t.cs() == "atop" || t.cs() == "brace"
1807 || t.cs() == "brack") {
1808 MathAtom at = createInsetMath(t.cs(), buf);
1809 at.nucleus()->cell(0) = *cell;
1811 parse(at.nucleus()->cell(1), flags, mode);
1812 cell->push_back(at);
1816 else if (t.cs() == "color") {
1817 docstring const color = parse_verbatim_item();
1818 cell->push_back(MathAtom(new InsetMathColor(buf, true, color)));
1819 parse(cell->back().nucleus()->cell(0), flags, mode);
1823 else if (t.cs() == "textcolor") {
1824 docstring const color = parse_verbatim_item();
1825 cell->push_back(MathAtom(new InsetMathColor(buf, false, color)));
1826 parse(cell->back().nucleus()->cell(0), FLAG_ITEM, InsetMath::TEXT_MODE);
1829 else if (t.cs() == "normalcolor") {
1830 cell->push_back(createInsetMath(t.cs(), buf));
1831 parse(cell->back().nucleus()->cell(0), flags, mode);
1835 else if (t.cs() == "substack") {
1836 cell->push_back(createInsetMath(t.cs(), buf));
1837 parse2(cell->back(), FLAG_ITEM, mode, false);
1838 // Delete empty last row if present
1839 InsetMathGrid & subgrid =
1840 *(cell->back().nucleus()->asGridInset());
1841 if (subgrid.nrows() > 1)
1842 delEmptyLastRow(subgrid);
1845 else if (t.cs() == "xymatrix") {
1846 odocstringstream os;
1847 while (good() && nextToken().cat() != catBegin)
1848 os << getToken().asInput();
1849 cell->push_back(createInsetMath(t.cs() + os.str(), buf));
1850 parse2(cell->back(), FLAG_ITEM, mode, false);
1851 // Delete empty last row if present
1852 InsetMathGrid & subgrid =
1853 *(cell->back().nucleus()->asGridInset());
1854 if (subgrid.nrows() > 1)
1855 delEmptyLastRow(subgrid);
1858 else if (t.cs() == "Diagram") {
1859 odocstringstream os;
1860 while (good() && nextToken().cat() != catBegin)
1861 os << getToken().asInput();
1862 cell->push_back(createInsetMath(t.cs() + os.str(), buf));
1863 parse2(cell->back(), FLAG_ITEM, mode, false);
1866 else if (t.cs() == "framebox" || t.cs() == "makebox") {
1867 cell->push_back(createInsetMath(t.cs(), buf));
1868 parse(cell->back().nucleus()->cell(0), FLAG_OPTION, InsetMath::TEXT_MODE);
1869 parse(cell->back().nucleus()->cell(1), FLAG_OPTION, InsetMath::TEXT_MODE);
1870 parse(cell->back().nucleus()->cell(2), FLAG_ITEM, InsetMath::TEXT_MODE);
1873 else if (t.cs() == "tag") {
1874 if (nextToken().character() == '*') {
1876 cell->push_back(createInsetMath(t.cs() + '*', buf));
1878 cell->push_back(createInsetMath(t.cs(), buf));
1879 parse(cell->back().nucleus()->cell(0), FLAG_ITEM, InsetMath::TEXT_MODE);
1882 else if (t.cs() == "hspace") {
1883 bool const prot = nextToken().character() == '*';
1886 docstring const & name = t.cs();
1887 docstring const arg = parse_verbatim_item();
1889 if (prot && arg == "\\fill")
1890 cell->push_back(MathAtom(new InsetMathSpace(buf, "hspace*{\\fill}", "")));
1891 else if (isValidLength(to_utf8(arg), &length))
1892 cell->push_back(MathAtom(new InsetMathSpace(buf, length, prot)));
1894 // Since the Length class cannot use length variables
1895 // we must not create an InsetMathSpace.
1896 cell->push_back(MathAtom(new InsetMathMacro(buf, name)));
1898 mathed_parse_cell(ar, '{' + arg + '}', mode_);
1903 else if (t.cs() == "smash") {
1905 if (nextToken().asInput() == "[") {
1906 // Since the phantom inset cannot handle optional arguments
1907 // other than b and t, we must not create an InsetMathPhantom
1908 // if opt is different from b and t (bug 8967).
1909 docstring const opt = parse_verbatim_option();
1910 if (opt == "t" || opt == "b") {
1911 cell->push_back(createInsetMath(t.cs() + opt, buf));
1912 parse(cell->back().nucleus()->cell(0), FLAG_ITEM, mode);
1914 docstring const arg = parse_verbatim_item();
1915 cell->push_back(MathAtom(new InsetMathMacro(buf, t.cs())));
1917 mathed_parse_cell(ar, '[' + opt + ']', mode_);
1920 mathed_parse_cell(ar, '{' + arg + '}', mode_);
1925 cell->push_back(createInsetMath(t.cs(), buf));
1926 parse(cell->back().nucleus()->cell(0), FLAG_ITEM, mode);
1931 else if (t.cs() == "infer") {
1933 parse(ar, FLAG_OPTION, mode);
1934 cell->push_back(createInsetMath(t.cs(), buf));
1935 parse2(cell->back(), FLAG_ITEM, mode, false);
1939 else if (t.cs() == "lyxmathsym") {
1941 if (getToken().cat() != catBegin) {
1942 error("'{' expected in \\" + t.cs());
1947 CatCode cat = nextToken().cat();
1948 while (good() && (count || cat != catEnd)) {
1949 if (cat == catBegin)
1951 else if (cat == catEnd)
1953 cmd += getToken().asInput();
1954 cat = nextToken().cat();
1956 if (getToken().cat() != catEnd) {
1957 error("'}' expected in \\" + t.cs());
1963 cmd = Encodings::fromLaTeXCommand(cmd,
1964 Encodings::MATH_CMD | Encodings::TEXT_CMD,
1966 for (char_type c : cmd)
1967 cell->push_back(MathAtom(new InsetMathChar(buf, c)));
1969 char_type c = rem[0];
1970 cell->push_back(MathAtom(new InsetMathChar(buf, c)));
1971 cmd = rem.substr(1);
1975 } while (!cmd.empty());
1978 else if (!t.cs().empty()) {
1979 bool const no_mhchem =
1980 (t.cs() == "ce" || t.cs() == "cf")
1981 && buf && buf->params().use_package("mhchem") ==
1982 BufferParams::package_off;
1984 bool const is_user_macro = no_mhchem ||
1985 (buf && ((mode_ & Parse::TRACKMACRO)
1986 ? buf->usermacros.count(t.cs()) != 0
1987 : buf->getMacro(t.cs(), false) != 0));
1989 latexkeys const * l = in_word_set(t.cs());
1990 if (l && !is_user_macro) {
1991 if (l->inset == "big") {
1993 docstring const delim = getToken().asInput();
1994 if (InsetMathBig::isBigInsetDelim(delim))
1995 cell->push_back(MathAtom(
1996 new InsetMathBig(buf, t.cs(), delim)));
1998 cell->push_back(createInsetMath(t.cs(), buf));
1999 // For some reason delim.empty()
2000 // is always false here
2006 else if (l->inset == "font") {
2007 cell->push_back(createInsetMath(t.cs(), buf));
2008 parse(cell->back().nucleus()->cell(0),
2009 FLAG_ITEM, asMode(mode, l->extra));
2012 else if (l->inset == "oldfont" || l->inset == "textsize") {
2013 cell->push_back(createInsetMath(t.cs(), buf));
2014 parse(cell->back().nucleus()->cell(0),
2015 flags | FLAG_ALIGN, asMode(mode, l->extra));
2016 if (prevToken().cat() != catAlign &&
2017 prevToken().cs() != "\\")
2022 else if (l->inset == "style") {
2023 cell->push_back(createInsetMath(t.cs(), buf));
2024 parse(cell->back().nucleus()->cell(0),
2025 flags | FLAG_ALIGN, mode);
2026 if (prevToken().cat() != catAlign &&
2027 prevToken().cs() != "\\")
2032 else if (l->inset == "underset" || l->inset == "overset") {
2033 cell->push_back(createInsetMath(t.cs(), buf));
2034 parse(cell->back().nucleus()->cell(1), FLAG_ITEM, mode);
2035 parse(cell->back().nucleus()->cell(0), FLAG_ITEM, mode);
2039 MathAtom at = createInsetMath(t.cs(), buf);
2040 for (idx_type i = 0; i < at->nargs(); ++i)
2041 parse(at.nucleus()->cell(i),
2042 FLAG_ITEM, asMode(mode, l->extra));
2043 cell->push_back(at);
2048 bool is_unicode_symbol = false;
2049 if (mode == InsetMath::TEXT_MODE && !is_user_macro) {
2051 docstring cmd = prevToken().asInput();
2052 CatCode cat = nextToken().cat();
2053 if (cat == catBegin) {
2055 while (good() && (count || cat != catEnd)) {
2056 cat = nextToken().cat();
2057 cmd += getToken().asInput();
2059 if (cat == catBegin)
2061 else if (cat == catEnd)
2067 char_type c = Encodings::fromLaTeXCommand(cmd,
2068 Encodings::MATH_CMD | Encodings::TEXT_CMD,
2069 is_combining, termination);
2071 if (cat == catLetter)
2073 cmd += getToken().asInput();
2075 if (cat == catLetter)
2077 c = Encodings::fromLaTeXCommand(cmd,
2078 Encodings::MATH_CMD | Encodings::TEXT_CMD,
2079 is_combining, termination);
2081 if (c && buf && buf->params().encoding().encodable(c)) {
2083 if (nextToken().cat() == catBegin) {
2085 if (nextToken().cat() == catEnd) {
2090 while (nextToken().cat() == catSpace) {
2095 is_unicode_symbol = true;
2096 cell->push_back(MathAtom(new InsetMathChar(buf, c)));
2098 while (num_tokens--)
2102 if (!is_unicode_symbol) {
2103 MathAtom at = is_user_macro ?
2104 MathAtom(new InsetMathMacro(buf, t.cs()))
2105 : createInsetMath(t.cs(), buf);
2106 InsetMath::mode_type m = mode;
2107 //if (m == InsetMath::UNDECIDED_MODE)
2108 //lyxerr << "default creation: m1: " << m << endl;
2109 if (at->currentMode() != InsetMath::UNDECIDED_MODE)
2110 m = at->currentMode();
2111 //lyxerr << "default creation: m2: " << m << endl;
2113 // this fails on \bigg[...\bigg]
2115 //parse(opt, FLAG_OPTION, InsetMath::VERBATIM_MODE);
2116 //if (!opt.empty()) {
2118 // at.nucleus()->cell(0) = opt;
2120 for (idx_type i = start; i < at->nargs(); ++i) {
2121 parse(at.nucleus()->cell(i), FLAG_ITEM, m);
2122 if (mode == InsetMath::MATH_MODE)
2125 cell->push_back(at);
2131 if (flags & FLAG_LEAVE) {
2140 } // anonymous namespace
2143 // FIXME This will likely need some work.
2144 char const * latexkeys::MathMLtype() const
2146 // Consider as identifier (mml:mi): ordinary and alphabetical characters.
2147 if (extra == "mathord" || extra == "mathalpha")
2149 // Consider as operators (mml:mo): everything else.
2154 bool mathed_parse_cell(MathData & ar, docstring const & str, Parse::flags f)
2156 return Parser(str, f, ar.buffer()).parse(ar, 0, (f & Parse::TEXTMODE) ?
2157 InsetMath::TEXT_MODE : InsetMath::MATH_MODE);
2161 bool mathed_parse_cell(MathData & ar, istream & is, Parse::flags f)
2163 return Parser(is, f, ar.buffer()).parse(ar, 0, (f & Parse::TEXTMODE) ?
2164 InsetMath::TEXT_MODE : InsetMath::MATH_MODE);
2168 bool mathed_parse_normal(Buffer * buf, MathAtom & t, docstring const & str,
2171 return Parser(str, f, buf).parse(t);
2175 bool mathed_parse_normal(Buffer * buf, MathAtom & t, Lexer & lex,
2178 return Parser(lex, f, buf).parse(t);
2182 bool mathed_parse_normal(InsetMathGrid & grid, docstring const & str,
2185 return Parser(str, f, &grid.buffer()).parse1(grid, 0, (f & Parse::TEXTMODE) ?
2186 InsetMath::TEXT_MODE : InsetMath::MATH_MODE, false);
2192 fill(theCatcode, theCatcode + 128, catOther);
2193 fill(theCatcode + 'a', theCatcode + 'z' + 1, catLetter);
2194 fill(theCatcode + 'A', theCatcode + 'Z' + 1, catLetter);
2196 theCatcode[int('\\')] = catEscape;
2197 theCatcode[int('{')] = catBegin;
2198 theCatcode[int('}')] = catEnd;
2199 theCatcode[int('$')] = catMath;
2200 theCatcode[int('&')] = catAlign;
2201 theCatcode[int('\n')] = catNewline;
2202 theCatcode[int('#')] = catParameter;
2203 theCatcode[int('^')] = catSuper;
2204 theCatcode[int('_')] = catSub;
2205 theCatcode[int(0x7f)] = catIgnore;
2206 theCatcode[int(' ')] = catSpace;
2207 theCatcode[int('\t')] = catSpace;
2208 theCatcode[int('\r')] = catNewline;
2209 theCatcode[int('~')] = catActive;
2210 theCatcode[int('%')] = catComment;