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 wether 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 wether 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 instanciate
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() == '[') {
747 Token t = getToken();
748 for (t = getToken(); t.character() != ']' && good(); t = getToken()) {
749 if (t.cat() == catBegin) {
751 res += '{' + parse_verbatim_item() + '}';
760 docstring Parser::parse_verbatim_item()
764 if (nextToken().cat() == catBegin) {
765 Token t = getToken();
766 for (t = getToken(); t.cat() != catEnd && good(); t = getToken()) {
767 if (t.cat() == catBegin) {
769 res += '{' + parse_verbatim_item() + '}';
779 bool Parser::parse(MathData & array, unsigned flags, mode_type mode)
781 InsetMathGrid grid(buffer_, 1, 1);
782 parse1(grid, flags, mode, false);
783 array = grid.cell(0);
788 void Parser::parse2(MathAtom & at, const unsigned flags, const mode_type mode,
791 parse1(*(at.nucleus()->asGridInset()), flags, mode, numbered);
795 bool Parser::parse1(InsetMathGrid & grid, unsigned flags,
796 const mode_type mode, const bool numbered)
799 InsetMathGrid::row_type cellrow = 0;
800 InsetMathGrid::col_type cellcol = 0;
801 MathData * cell = &grid.cell(grid.index(cellrow, cellcol));
802 Buffer * buf = buffer_;
804 if (grid.asHullInset())
805 grid.asHullInset()->numbered(cellrow, numbered);
808 //lyxerr << " flags: " << flags << endl;
809 //lyxerr << " mode: " << mode << endl;
810 //lyxerr << "grid: " << grid << endl;
813 Token const & t = getToken();
816 lyxerr << "t: " << t << " flags: " << flags << endl;
817 lyxerr << "mode: " << mode << endl;
822 if (flags & FLAG_ITEM) {
824 if (t.cat() == catBegin) {
825 // skip the brace and collect everything to the next matching
827 parse1(grid, FLAG_BRACE_LAST, mode, numbered);
831 // handle only this single token, leave the loop if done
836 if (flags & FLAG_BRACED) {
837 if (t.cat() == catSpace)
840 if (t.cat() != catBegin) {
841 error("opening brace expected");
845 // skip the brace and collect everything to the next matching
847 flags = FLAG_BRACE_LAST;
851 if (flags & FLAG_OPTION) {
852 if (t.cat() == catOther && t.character() == '[') {
854 parse(ar, FLAG_BRACK_LAST, mode);
857 // no option found, put back token and we are done
866 if (t.cat() == catMath) {
867 if (mode != InsetMath::MATH_MODE) {
868 // we are inside some text mode thingy, so opening new math is allowed
869 Token const & n = getToken();
870 if (n.cat() == catMath) {
871 // TeX's $$...$$ syntax for displayed math
872 if (mode == InsetMath::UNDECIDED_MODE) {
873 cell->push_back(MathAtom(new InsetMathHull(buf, hullEquation)));
874 parse2(cell->back(), FLAG_SIMPLE, InsetMath::MATH_MODE, false);
875 getToken(); // skip the second '$' token
877 // This is not an outer hull and display math is
878 // not allowed inside text mode environments.
879 error("bad math environment $$");
883 // simple $...$ stuff
885 if (mode == InsetMath::UNDECIDED_MODE) {
886 cell->push_back(MathAtom(new InsetMathHull(buf, hullSimple)));
887 parse2(cell->back(), FLAG_SIMPLE, InsetMath::MATH_MODE, false);
889 // Don't create nested math hulls (bug #5392)
890 cell->push_back(MathAtom(new InsetMathEnsureMath(buf)));
891 parse(cell->back().nucleus()->cell(0), FLAG_SIMPLE, InsetMath::MATH_MODE);
896 else if (flags & FLAG_SIMPLE) {
897 // this is the end of the formula
902 Token const & n = getToken();
903 if (n.cat() == catMath) {
904 error("something strange in the parser");
907 // This is inline math ($...$), but the parser thinks we are
908 // already in math mode and latex would issue an error, unless we
909 // are inside a text mode user macro. We have no way to tell, so
910 // let's play safe by using \ensuremath, as it will work in any case.
912 cell->push_back(MathAtom(new InsetMathEnsureMath(buf)));
913 parse(cell->back().nucleus()->cell(0), FLAG_SIMPLE, InsetMath::MATH_MODE);
918 else if (t.cat() == catLetter)
919 cell->push_back(MathAtom(new InsetMathChar(t.character())));
921 else if (t.cat() == catSpace && mode != InsetMath::MATH_MODE) {
922 if (cell->empty() || cell->back()->getChar() != ' ')
923 cell->push_back(MathAtom(new InsetMathChar(t.character())));
926 else if (t.cat() == catNewline && mode != InsetMath::MATH_MODE) {
927 if (cell->empty() || cell->back()->getChar() != ' ')
928 cell->push_back(MathAtom(new InsetMathChar(' ')));
931 else if (t.cat() == catParameter) {
932 Token const & n = nextToken();
933 char_type c = n.character();
934 if (c && '0' < c && c <= '9') {
935 cell->push_back(MathAtom(new InsetMathMacroArgument(c - '0')));
938 cell->push_back(MathAtom(new InsetMathHash()));
941 else if (t.cat() == catActive)
942 cell->push_back(MathAtom(new InsetMathSpace(string(1, t.character()), "")));
944 else if (t.cat() == catBegin) {
945 bool const inbraces = nextToken().cat() == catBegin ||
946 (!cell->empty() && cell->back()->asMacro());
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 InsetMathMacro const * ma = !inbraces && ar.size() ? ar[0]->asMacro() : 0;
952 InsetMathChar const * mc = ma && ar.size() > 1 ? ar[1]->asCharInset(): 0;
953 bool braced = mc && mc->getChar() == '[';
954 // If this is a macro, it may have optional
955 // arguments, even if only defaults are used.
956 // In this case, there is no following '['.
957 if (!inbraces && !braced && ma && buf) {
958 if (mode_ & Parse::TRACKMACRO)
959 braced = buf->usermacros_with_opts.count(ma->name());
961 MacroData const * md = buf->getMacro(ma->name(), false);
962 braced = md && md->optionals();
965 if ((ar.size() == 1 && ar[0]->extraBraces()) || braced)
968 cell->push_back(MathAtom(new InsetMathBrace(ar)));
971 else if (t.cat() == catEnd) {
972 if (flags & FLAG_BRACE_LAST)
974 error("found '}' unexpectedly");
975 //LASSERT(false, /**/);
976 //add(cell, '}', LM_TC_TEX);
979 else if (t.cat() == catAlign) {
980 //lyxerr << " column now " << (cellcol + 1)
981 // << " max: " << grid.ncols() << endl;
982 if (flags & FLAG_ALIGN)
984 if (addCol(grid, cellcol))
985 cell = &grid.cell(grid.index(cellrow, cellcol));
988 else if (t.cat() == catSuper || t.cat() == catSub) {
989 bool up = (t.cat() == catSuper);
990 // we need no new script inset if the last thing was a scriptinset,
991 // which has that script already not the same script already
993 cell->push_back(MathAtom(new InsetMathScript(buf, up)));
994 else if (cell->back()->asScriptInset() &&
995 !cell->back()->asScriptInset()->has(up))
996 cell->back().nucleus()->asScriptInset()->ensure(up);
997 else if (cell->back()->asScriptInset())
998 cell->push_back(MathAtom(new InsetMathScript(buf, up)));
1000 cell->back() = MathAtom(new InsetMathScript(buf, cell->back(), up));
1001 InsetMathScript * p = cell->back().nucleus()->asScriptInset();
1002 // special handling of {}-bases
1003 // Here we could remove the brace inset for things
1004 // like {a'}^2 and add the braces back in
1005 // InsetMathScript::write().
1006 // We do not do it, since it is not possible to detect
1007 // reliably whether the braces are needed because the
1008 // nucleus contains more than one symbol, or whether
1009 // they are needed for unknown commands like \xx{a}_0
1010 // or \yy{a}{b}_0. This was done in revision 14819
1011 // in an unreliable way. See this thread
1012 // http://www.mail-archive.com/lyx-devel%40lists.lyx.org/msg104917.html
1013 // for more details.
1014 // However, we remove empty braces because they look
1015 // ugly on screen and we are sure that they were added
1016 // by the write() method (and will be re-added on save).
1017 if (p->nuc().size() == 1 &&
1018 p->nuc().back()->asBraceInset() &&
1019 p->nuc().back()->asBraceInset()->cell(0).empty())
1022 parse(p->cell(p->idxOfScript(up)), FLAG_ITEM, mode);
1029 else if (t.character() == ']' && (flags & FLAG_BRACK_LAST)) {
1030 //lyxerr << "finished reading option" << endl;
1034 else if (t.cat() == catOther) {
1035 char_type c = t.character();
1036 if (!Encodings::isUnicodeTextOnly(c)
1037 || mode_ & Parse::VERBATIM
1038 || !(mode_ & Parse::USETEXT)
1039 || mode == InsetMath::TEXT_MODE) {
1040 cell->push_back(MathAtom(new InsetMathChar(c)));
1042 MathAtom at = createInsetMath("text", buf);
1043 at.nucleus()->cell(0).push_back(MathAtom(new InsetMathChar(c)));
1044 while (nextToken().cat() == catOther
1045 && Encodings::isUnicodeTextOnly(nextToken().character())) {
1046 c = getToken().character();
1047 at.nucleus()->cell(0).push_back(MathAtom(new InsetMathChar(c)));
1049 cell->push_back(at);
1053 else if (t.cat() == catComment) {
1056 Token const & tt = getToken();
1057 if (tt.cat() == catNewline)
1061 cell->push_back(MathAtom(new InsetMathComment(buf, s)));
1066 // control sequences
1069 else if (t.cs() == "lyxlock") {
1071 cell->back().nucleus()->lock(true);
1074 else if ((t.cs() == "global" && nextToken().cs() == "def") ||
1076 if (t.cs() == "global")
1080 docstring name = getToken().cs();
1085 while (good() && nextToken().cat() != catBegin) {
1086 pars += getToken().cs();
1093 parse(def, FLAG_ITEM, InsetMath::UNDECIDED_MODE);
1095 // is a version for display attached?
1098 if (nextToken().cat() == catBegin)
1099 parse(display, FLAG_ITEM, InsetMath::MATH_MODE);
1101 cell->push_back(MathAtom(new InsetMathMacroTemplate(buf,
1102 name, nargs, 0, MacroTypeDef,
1103 vector<MathData>(), def, display)));
1105 if (buf && (mode_ & Parse::TRACKMACRO))
1106 buf->usermacros.insert(name);
1109 else if (t.cs() == "newcommand" ||
1110 t.cs() == "renewcommand" ||
1111 t.cs() == "newlyxcommand") {
1113 if (getToken().cat() != catBegin) {
1114 error("'{' in \\newcommand expected (1) ");
1117 docstring name = getToken().cs();
1118 if (getToken().cat() != catEnd) {
1119 error("'}' in \\newcommand expected");
1124 docstring const arg = getArg('[', ']');
1127 nargs = convert<int>(arg);
1129 // optional argument given?
1132 vector<MathData> optionalValues;
1133 while (nextToken().character() == '[') {
1135 optionalValues.push_back(MathData());
1136 parse(optionalValues[optionals], FLAG_BRACK_LAST, mode);
1141 parse(def, FLAG_ITEM, InsetMath::UNDECIDED_MODE);
1143 // is a version for display attached?
1146 if (nextToken().cat() == catBegin)
1147 parse(display, FLAG_ITEM, InsetMath::MATH_MODE);
1149 cell->push_back(MathAtom(new InsetMathMacroTemplate(buf,
1150 name, nargs, optionals, MacroTypeNewcommand,
1151 optionalValues, def, display)));
1153 if (buf && (mode_ & Parse::TRACKMACRO)) {
1154 buf->usermacros.insert(name);
1156 buf->usermacros_with_opts.insert(name);
1160 else if (t.cs() == "newcommandx" ||
1161 t.cs() == "renewcommandx") {
1162 // \newcommandx{\foo}[2][usedefault, addprefix=\global,1=default]{#1,#2}
1165 if (nextToken().cat() == catBegin) {
1167 name = getToken().cs();
1168 if (getToken().cat() != catEnd) {
1169 error("'}' in \\newcommandx expected");
1173 name = getToken().cs();
1176 docstring const arg = getArg('[', ']');
1178 error("[num] in \\newcommandx expected");
1181 int nargs = convert<int>(arg);
1185 vector<MathData> optionalValues;
1186 if (nextToken().character() == '[') {
1190 // handle 'opt=value' options, separated by ','.
1192 while (nextToken().character() != ']' && good()) {
1193 if (nextToken().character() >= '1'
1194 && nextToken().character() <= '9') {
1195 // optional value -> get parameter number
1196 int n = getChar() - '0';
1198 error("Arity of \\newcommandx too low "
1199 "for given optional parameter.");
1204 if (getToken().character() != '=') {
1205 error("'=' and optional parameter value "
1206 "expected for \\newcommandx");
1211 int optNum = max(size_t(n), optionalValues.size());
1212 optionalValues.resize(optNum);
1213 optionalValues[n - 1].clear();
1214 while (nextToken().character() != ']'
1215 && nextToken().character() != ',') {
1217 parse(data, FLAG_ITEM, InsetMath::UNDECIDED_MODE);
1218 optionalValues[n - 1].append(data);
1220 optionals = max(n, optionals);
1221 } else if (nextToken().cat() == catLetter) {
1222 // we in fact ignore every non-optional
1227 while (nextToken().cat() == catLetter)
1233 if (nextToken().character() == '=') {
1235 while (nextToken().character() != ']'
1236 && nextToken().character() != ',')
1237 parse(value, FLAG_ITEM,
1238 InsetMath::UNDECIDED_MODE);
1241 error("option for \\newcommandx expected");
1247 if (nextToken().character() == ',') {
1250 } else if (nextToken().character() != ']') {
1251 error("Expecting ',' or ']' in options "
1252 "of \\newcommandx");
1265 parse(def, FLAG_ITEM, InsetMath::UNDECIDED_MODE);
1267 // is a version for display attached?
1270 if (nextToken().cat() == catBegin)
1271 parse(display, FLAG_ITEM, InsetMath::MATH_MODE);
1273 cell->push_back(MathAtom(new InsetMathMacroTemplate(buf,
1274 name, nargs, optionals, MacroTypeNewcommandx,
1275 optionalValues, def, display)));
1277 if (buf && (mode_ & Parse::TRACKMACRO)) {
1278 buf->usermacros.insert(name);
1280 buf->usermacros_with_opts.insert(name);
1284 else if (t.cs() == "(") {
1285 if (mode == InsetMath::UNDECIDED_MODE) {
1286 cell->push_back(MathAtom(new InsetMathHull(buf, hullSimple)));
1287 parse2(cell->back(), FLAG_SIMPLE2, InsetMath::MATH_MODE, false);
1289 // Don't create nested math hulls (bug #5392)
1290 cell->push_back(MathAtom(new InsetMathEnsureMath(buf)));
1291 parse(cell->back().nucleus()->cell(0), FLAG_SIMPLE2, InsetMath::MATH_MODE);
1295 else if (t.cs() == "[") {
1296 if (mode != InsetMath::UNDECIDED_MODE) {
1297 error("bad math environment [");
1300 cell->push_back(MathAtom(new InsetMathHull(buf, hullEquation)));
1301 parse2(cell->back(), FLAG_EQUATION, InsetMath::MATH_MODE, false);
1304 else if (t.cs() == "protect")
1305 // ignore \\protect, will hopefully be re-added during output
1308 else if (t.cs() == "end") {
1309 if (flags & FLAG_END) {
1310 // eat environment name
1311 docstring const name = getArg('{', '}');
1312 if (environments_.empty())
1313 error("'found \\end{" + name +
1314 "}' without matching '\\begin{" +
1316 else if (name != environments_.back())
1317 error("'\\end{" + name +
1318 "}' does not match '\\begin{" +
1319 environments_.back() + "}'");
1321 environments_.pop_back();
1322 // Delete empty last row in matrix
1324 // If you abuse InsetMathGrid for
1325 // non-matrix like structures you
1326 // probably need to refine this test.
1327 // Right now we only have to test for
1328 // single line hull insets.
1329 if (grid.nrows() > 1 && innerHull(name))
1330 delEmptyLastRow(grid);
1334 error("found 'end' unexpectedly");
1337 else if (t.cs() == ")") {
1338 if (flags & FLAG_SIMPLE2)
1340 error("found '\\)' unexpectedly");
1343 else if (t.cs() == "]") {
1344 if (flags & FLAG_EQUATION)
1346 error("found '\\]' unexpectedly");
1349 else if (t.cs() == "\\") {
1350 if (flags & FLAG_ALIGN)
1352 bool starred = false;
1354 if (nextToken().asInput() == "*") {
1357 } else if (nextToken().asInput() == "[")
1358 arg = getArg('[', ']');
1360 error("missing token after \\\\");
1361 // skip "{}" added in front of "[" (the
1362 // counterpart is in InsetMathGrid::eolString())
1363 // skip spaces because formula could come from tex2lyx
1364 bool skipBraces = false;
1366 if (nextToken().cat() == catBegin) {
1368 if (nextToken().cat() == catEnd) {
1372 if (nextToken().asInput() == "[")
1381 bool const added = addRow(grid, cellrow, arg, !starred);
1384 if (grid.asHullInset())
1385 grid.asHullInset()->numbered(
1387 cell = &grid.cell(grid.index(cellrow,
1392 else if (t.cs() == "multicolumn" && grid.handlesMulticolumn()) {
1393 // if the columns are specified numerically,
1394 // extract column count and insert dummy cells,
1395 // otherwise parse it as an user macro
1397 parse(count, FLAG_ITEM, mode);
1399 // limit arbitrarily to 100 columns
1400 if (extractNumber(count, cols) && cols > 0 && cols < 100) {
1401 // resize the table if necessary
1402 size_t first = grid.index(cellrow, cellcol);
1403 for (int i = 1; i < cols; ++i) {
1404 if (addCol(grid, cellcol)) {
1405 size_t const idx = grid.index(cellrow, cellcol);
1406 grid.cellinfo(idx).multi_ =
1407 InsetMathGrid::CELL_PART_OF_MULTICOLUMN;
1411 // the first cell is the real thing, not a dummy
1412 cell = &grid.cell(first);
1413 grid.cellinfo(first).multi_ =
1414 InsetMathGrid::CELL_BEGIN_OF_MULTICOLUMN;
1416 // read special alignment
1418 parse(align, FLAG_ITEM, mode);
1419 grid.cellinfo(first).align_ = asString(align);
1421 // parse the remaining contents into the "real" cell
1422 parse(*cell, FLAG_ITEM, mode);
1424 MathAtom at = MathAtom(new InsetMathMacro(buf, t.cs()));
1425 cell->push_back(at);
1426 cell->push_back(MathAtom(new InsetMathBrace(count)));
1430 else if (t.cs() == "limits" || t.cs() == "nolimits") {
1431 CatCode const cat = nextToken().cat();
1432 if (cat == catSuper || cat == catSub)
1433 limits = t.cs() == "limits" ? 1 : -1;
1435 MathAtom at = createInsetMath(t.cs(), buf);
1436 cell->push_back(at);
1440 // \notag is the same as \nonumber if amsmath is used
1441 else if ((t.cs() == "nonumber" || t.cs() == "notag") &&
1443 grid.asHullInset()->numbered(cellrow, false);
1445 else if (t.cs() == "number" && grid.asHullInset())
1446 grid.asHullInset()->numbered(cellrow, true);
1448 else if (t.cs() == "hline") {
1449 grid.rowinfo(cellrow).lines_ ++;
1452 else if (t.cs() == "sqrt") {
1454 parse(ar, FLAG_OPTION, mode);
1456 cell->push_back(MathAtom(new InsetMathRoot(buf)));
1457 cell->back().nucleus()->cell(1) = ar;
1459 cell->push_back(MathAtom(new InsetMathSqrt(buf)));
1460 parse(cell->back().nucleus()->cell(0), FLAG_ITEM, mode);
1463 else if (t.cs() == "cancelto") {
1465 parse(ar, FLAG_ITEM, mode);
1466 cell->push_back(MathAtom(new InsetMathCancelto(buf)));
1467 cell->back().nucleus()->cell(1) = ar;
1468 parse(cell->back().nucleus()->cell(0), FLAG_ITEM, mode);
1471 else if (t.cs() == "unit") {
1472 // Allowed formats \unit[val]{unit}
1474 parse(ar, FLAG_OPTION, mode);
1476 cell->push_back(MathAtom(new InsetMathFrac(buf, InsetMathFrac::UNIT)));
1477 cell->back().nucleus()->cell(0) = ar;
1478 parse(cell->back().nucleus()->cell(1), FLAG_ITEM, mode);
1480 cell->push_back(MathAtom(new InsetMathFrac(buf, InsetMathFrac::UNIT, 1)));
1481 parse(cell->back().nucleus()->cell(0), FLAG_ITEM, mode);
1485 else if (t.cs() == "unitfrac") {
1486 // Here allowed formats are \unitfrac[val]{num}{denom}
1488 parse(ar, FLAG_OPTION, mode);
1490 cell->push_back(MathAtom(new InsetMathFrac(buf, InsetMathFrac::UNITFRAC, 3)));
1491 cell->back().nucleus()->cell(2) = ar;
1493 cell->push_back(MathAtom(new InsetMathFrac(buf, InsetMathFrac::UNITFRAC)));
1495 parse(cell->back().nucleus()->cell(0), FLAG_ITEM, mode);
1496 parse(cell->back().nucleus()->cell(1), FLAG_ITEM, mode);
1499 else if (t.cs() == "cfrac") {
1500 // allowed formats are \cfrac[pos]{num}{denom}
1501 docstring const arg = getArg('[', ']');
1502 //lyxerr << "got so far: '" << arg << "'" << endl;
1504 cell->push_back(MathAtom(new InsetMathFrac(buf, InsetMathFrac::CFRACLEFT)));
1505 else if (arg == "r")
1506 cell->push_back(MathAtom(new InsetMathFrac(buf, InsetMathFrac::CFRACRIGHT)));
1507 else if (arg.empty() || arg == "c")
1508 cell->push_back(MathAtom(new InsetMathFrac(buf, InsetMathFrac::CFRAC)));
1510 error("found invalid optional argument");
1513 parse(cell->back().nucleus()->cell(0), FLAG_ITEM, mode);
1514 parse(cell->back().nucleus()->cell(1), FLAG_ITEM, mode);
1517 else if (t.cs() == "sideset") {
1518 // Here allowed formats are \sideset{_{bl}^{tl}}{_{br}^{tr}}{operator}
1520 InsetMathScript * script[2] = {0, 0};
1521 for (int i = 0; i < 2; ++i) {
1522 parse(ar[i], FLAG_ITEM, mode);
1523 if (ar[i].size() == 1)
1524 script[i] = ar[i][0].nucleus()->asScriptInset();
1526 bool const hasscript[2] = {script[0] ? true : false, script[1] ? true : false};
1527 cell->push_back(MathAtom(new InsetMathSideset(buf, hasscript[0], hasscript[1])));
1529 if (script[0]->hasDown())
1530 cell->back().nucleus()->cell(1) = script[0]->down();
1531 if (script[0]->hasUp())
1532 cell->back().nucleus()->cell(2) = script[0]->up();
1534 cell->back().nucleus()->cell(1) = ar[0];
1536 if (script[1]->hasDown())
1537 cell->back().nucleus()->cell(2 + hasscript[0]) = script[1]->down();
1538 if (script[1]->hasUp())
1539 cell->back().nucleus()->cell(3 + hasscript[0]) = script[1]->up();
1541 cell->back().nucleus()->cell(2 + hasscript[0]) = ar[1];
1542 parse(cell->back().nucleus()->cell(0), FLAG_ITEM, mode);
1545 else if (t.cs() == "stackrel") {
1546 // Here allowed formats are \stackrel[subscript]{superscript}{operator}
1548 parse(ar, FLAG_OPTION, mode);
1549 cell->push_back(MathAtom(new InsetMathStackrel(buf, !ar.empty())));
1551 cell->back().nucleus()->cell(2) = ar;
1552 parse(cell->back().nucleus()->cell(1), FLAG_ITEM, mode);
1553 parse(cell->back().nucleus()->cell(0), FLAG_ITEM, mode);
1556 else if (t.cs() == "xrightarrow" || t.cs() == "xleftarrow") {
1557 cell->push_back(createInsetMath(t.cs(), buf));
1558 parse(cell->back().nucleus()->cell(1), FLAG_OPTION, mode);
1559 parse(cell->back().nucleus()->cell(0), FLAG_ITEM, mode);
1562 else if (t.cs() == "xhookrightarrow" || t.cs() == "xhookleftarrow" ||
1563 t.cs() == "xRightarrow" || t.cs() == "xLeftarrow" ||
1564 t.cs() == "xleftrightarrow" || t.cs() == "xLeftrightarrow" ||
1565 t.cs() == "xrightharpoondown" || t.cs() == "xrightharpoonup" ||
1566 t.cs() == "xleftharpoondown" || t.cs() == "xleftharpoonup" ||
1567 t.cs() == "xleftrightharpoons" || t.cs() == "xrightleftharpoons" ||
1568 t.cs() == "xmapsto") {
1569 cell->push_back(createInsetMath(t.cs(), buf));
1570 parse(cell->back().nucleus()->cell(1), FLAG_OPTION, mode);
1571 parse(cell->back().nucleus()->cell(0), FLAG_ITEM, mode);
1574 else if (t.cs() == "ref" || t.cs() == "eqref" || t.cs() == "prettyref"
1575 || t.cs() == "nameref" || t.cs() == "pageref"
1576 || t.cs() == "vpageref" || t.cs() == "vref") {
1577 cell->push_back(MathAtom(new InsetMathRef(buf, t.cs())));
1578 docstring const opt = parse_verbatim_option();
1579 docstring const ref = parse_verbatim_item();
1581 cell->back().nucleus()->cell(1).push_back(
1582 MathAtom(new InsetMathString(opt)));
1584 cell->back().nucleus()->cell(0).push_back(
1585 MathAtom(new InsetMathString(ref)));
1588 else if (t.cs() == "left") {
1590 Token const & tl = getToken();
1591 // \| and \Vert are equivalent, and InsetMathDelim
1593 // FIXME: fix this in InsetMathDelim itself!
1594 docstring const l = tl.cs() == "|" ? from_ascii("Vert") : tl.asString();
1596 parse(ar, FLAG_RIGHT, mode);
1600 Token const & tr = getToken();
1601 docstring const r = tr.cs() == "|" ? from_ascii("Vert") : tr.asString();
1602 cell->push_back(MathAtom(new InsetMathDelim(buf, l, r, ar)));
1605 else if (t.cs() == "right") {
1606 if (flags & FLAG_RIGHT)
1608 //lyxerr << "got so far: '" << cell << "'" << endl;
1609 error("Unmatched right delimiter");
1613 else if (t.cs() == "begin") {
1614 docstring const name = getArg('{', '}');
1618 error("found invalid environment");
1622 environments_.push_back(name);
1624 if (name == "array" || name == "subarray") {
1625 docstring const valign = parse_verbatim_option() + 'c';
1626 docstring const halign = parse_verbatim_item();
1627 cell->push_back(MathAtom(new InsetMathArray(buf, name,
1628 InsetMathGrid::guessColumns(halign), 1, (char)valign[0], halign)));
1629 parse2(cell->back(), FLAG_END, mode, false);
1632 else if (name == "tabular") {
1633 docstring const valign = parse_verbatim_option() + 'c';
1634 docstring const halign = parse_verbatim_item();
1635 cell->push_back(MathAtom(new InsetMathTabular(buf, name,
1636 InsetMathGrid::guessColumns(halign), 1, (char)valign[0], halign)));
1637 parse2(cell->back(), FLAG_END, InsetMath::TEXT_MODE, false);
1640 else if (name == "split" || name == "cases") {
1641 cell->push_back(createInsetMath(name, buf));
1642 parse2(cell->back(), FLAG_END, mode, false);
1645 else if (name == "alignedat") {
1646 docstring const valign = parse_verbatim_option() + 'c';
1647 // ignore this for a while
1649 cell->push_back(MathAtom(new InsetMathSplit(buf, name, (char)valign[0])));
1650 parse2(cell->back(), FLAG_END, mode, false);
1653 else if (name == "math") {
1654 if (mode == InsetMath::UNDECIDED_MODE) {
1655 cell->push_back(MathAtom(new InsetMathHull(buf, hullSimple)));
1656 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, false);
1658 // Don't create nested math hulls (bug #5392)
1659 cell->push_back(MathAtom(new InsetMathEnsureMath(buf)));
1660 parse(cell->back().nucleus()->cell(0), FLAG_END, InsetMath::MATH_MODE);
1664 else if (name == "equation" || name == "equation*"
1665 || name == "displaymath") {
1666 if (mode != InsetMath::UNDECIDED_MODE) {
1667 error("bad math environment " + name);
1670 cell->push_back(MathAtom(new InsetMathHull(buf, hullEquation)));
1671 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, (name == "equation"));
1674 else if (name == "eqnarray" || name == "eqnarray*") {
1675 if (mode != InsetMath::UNDECIDED_MODE) {
1676 error("bad math environment " + name);
1679 cell->push_back(MathAtom(new InsetMathHull(buf, hullEqnArray)));
1680 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, !stared(name));
1683 else if (name == "align" || name == "align*") {
1684 if (mode == InsetMath::UNDECIDED_MODE) {
1685 cell->push_back(MathAtom(new InsetMathHull(buf, hullAlign)));
1686 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, !stared(name));
1688 cell->push_back(MathAtom(new InsetMathSplit(buf, name,
1689 'c', !stared(name))));
1690 parse2(cell->back(), FLAG_END, mode, !stared(name));
1694 else if (name == "flalign" || name == "flalign*") {
1695 if (mode != InsetMath::UNDECIDED_MODE) {
1696 error("bad math environment " + name);
1699 cell->push_back(MathAtom(new InsetMathHull(buf, hullFlAlign)));
1700 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, !stared(name));
1703 else if (name == "alignat" || name == "alignat*") {
1704 if (mode != InsetMath::UNDECIDED_MODE) {
1705 error("bad math environment " + name);
1708 // ignore this for a while
1710 cell->push_back(MathAtom(new InsetMathHull(buf, hullAlignAt)));
1711 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, !stared(name));
1714 else if (name == "xalignat" || name == "xalignat*") {
1715 if (mode != InsetMath::UNDECIDED_MODE) {
1716 error("bad math environment " + name);
1719 // ignore this for a while
1721 cell->push_back(MathAtom(new InsetMathHull(buf, hullXAlignAt)));
1722 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, !stared(name));
1725 else if (name == "xxalignat") {
1726 if (mode != InsetMath::UNDECIDED_MODE) {
1727 error("bad math environment " + name);
1730 // ignore this for a while
1732 cell->push_back(MathAtom(new InsetMathHull(buf, hullXXAlignAt)));
1733 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, !stared(name));
1736 else if (name == "multline" || name == "multline*") {
1737 if (mode != InsetMath::UNDECIDED_MODE) {
1738 error("bad math environment " + name);
1741 cell->push_back(MathAtom(new InsetMathHull(buf, hullMultline)));
1742 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, !stared(name));
1745 else if (name == "gather" || name == "gather*") {
1746 if (mode != InsetMath::UNDECIDED_MODE) {
1747 error("bad math environment " + name);
1750 cell->push_back(MathAtom(new InsetMathHull(buf, hullGather)));
1751 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, !stared(name));
1754 else if (latexkeys const * l = in_word_set(name)) {
1755 if (l->inset == "matrix") {
1756 cell->push_back(createInsetMath(name, buf));
1757 parse2(cell->back(), FLAG_END, mode, false);
1758 } else if (l->inset == "split") {
1759 docstring const valign = parse_verbatim_option() + 'c';
1760 cell->push_back(MathAtom(
1761 new InsetMathSplit(buf, name, (char)valign[0])));
1762 parse2(cell->back(), FLAG_END, mode, false);
1765 if (!(mode_ & Parse::QUIET)) {
1767 lyxerr << "found math environment `"
1769 << "' in symbols file with unsupported inset `"
1773 // create generic environment inset
1774 cell->push_back(MathAtom(new InsetMathEnv(buf, name)));
1775 parse(cell->back().nucleus()->cell(0), FLAG_END, mode);
1781 if (!(mode_ & Parse::QUIET) &&
1782 !(mode_ & Parse::TRACKMACRO)) {
1784 lyxerr << "found unknown math environment '"
1785 << to_utf8(name) << "'" << endl;
1787 // create generic environment inset
1788 cell->push_back(MathAtom(new InsetMathEnv(buf, name)));
1789 parse(cell->back().nucleus()->cell(0), FLAG_END, mode);
1793 else if (t.cs() == "kern" || t.cs() == "mkern") {
1798 Token const & tt = getToken();
1802 while (num_tokens--)
1806 s += tt.character();
1807 if (isValidLength(to_utf8(s)))
1811 cell->push_back(MathAtom(new InsetMathMacro(buf, t.cs())));
1813 cell->push_back(MathAtom(new InsetMathKern(s)));
1816 else if (t.cs() == "label") {
1817 // FIXME: This is swallowed in inline formulas
1818 docstring label = parse_verbatim_item();
1821 if (grid.asHullInset()) {
1822 grid.asHullInset()->label(cellrow, label);
1823 grid.asHullInset()->numbered(cellrow, true);
1825 cell->push_back(createInsetMath(t.cs(), buf));
1826 cell->push_back(MathAtom(new InsetMathBrace(ar)));
1830 else if (t.cs() == "choose" || t.cs() == "over"
1831 || t.cs() == "atop" || t.cs() == "brace"
1832 || t.cs() == "brack") {
1833 MathAtom at = createInsetMath(t.cs(), buf);
1834 at.nucleus()->cell(0) = *cell;
1836 parse(at.nucleus()->cell(1), flags, mode);
1837 cell->push_back(at);
1841 else if (t.cs() == "color") {
1842 docstring const color = parse_verbatim_item();
1843 cell->push_back(MathAtom(new InsetMathColor(buf, true, color)));
1844 parse(cell->back().nucleus()->cell(0), flags, mode);
1848 else if (t.cs() == "textcolor") {
1849 docstring const color = parse_verbatim_item();
1850 cell->push_back(MathAtom(new InsetMathColor(buf, false, color)));
1851 parse(cell->back().nucleus()->cell(0), FLAG_ITEM, InsetMath::TEXT_MODE);
1854 else if (t.cs() == "normalcolor") {
1855 cell->push_back(createInsetMath(t.cs(), buf));
1856 parse(cell->back().nucleus()->cell(0), flags, mode);
1860 else if (t.cs() == "substack") {
1861 cell->push_back(createInsetMath(t.cs(), buf));
1862 parse2(cell->back(), FLAG_ITEM, mode, false);
1863 // Delete empty last row if present
1864 InsetMathGrid & subgrid =
1865 *(cell->back().nucleus()->asGridInset());
1866 if (subgrid.nrows() > 1)
1867 delEmptyLastRow(subgrid);
1870 else if (t.cs() == "xymatrix") {
1871 odocstringstream os;
1872 while (good() && nextToken().cat() != catBegin)
1873 os << getToken().asInput();
1874 cell->push_back(createInsetMath(t.cs() + os.str(), buf));
1875 parse2(cell->back(), FLAG_ITEM, mode, false);
1876 // Delete empty last row if present
1877 InsetMathGrid & subgrid =
1878 *(cell->back().nucleus()->asGridInset());
1879 if (subgrid.nrows() > 1)
1880 delEmptyLastRow(subgrid);
1883 else if (t.cs() == "Diagram") {
1884 odocstringstream os;
1885 while (good() && nextToken().cat() != catBegin)
1886 os << getToken().asInput();
1887 cell->push_back(createInsetMath(t.cs() + os.str(), buf));
1888 parse2(cell->back(), FLAG_ITEM, mode, false);
1891 else if (t.cs() == "framebox" || t.cs() == "makebox") {
1892 cell->push_back(createInsetMath(t.cs(), buf));
1893 parse(cell->back().nucleus()->cell(0), FLAG_OPTION, InsetMath::TEXT_MODE);
1894 parse(cell->back().nucleus()->cell(1), FLAG_OPTION, InsetMath::TEXT_MODE);
1895 parse(cell->back().nucleus()->cell(2), FLAG_ITEM, InsetMath::TEXT_MODE);
1898 else if (t.cs() == "tag") {
1899 if (nextToken().character() == '*') {
1901 cell->push_back(createInsetMath(t.cs() + '*', buf));
1903 cell->push_back(createInsetMath(t.cs(), buf));
1904 parse(cell->back().nucleus()->cell(0), FLAG_ITEM, InsetMath::TEXT_MODE);
1907 else if (t.cs() == "hspace") {
1908 bool const prot = nextToken().character() == '*';
1911 docstring const name = t.cs();
1912 docstring const arg = parse_verbatim_item();
1914 if (prot && arg == "\\fill")
1915 cell->push_back(MathAtom(new InsetMathSpace("hspace*{\\fill}", "")));
1916 else if (isValidLength(to_utf8(arg), &length))
1917 cell->push_back(MathAtom(new InsetMathSpace(length, prot)));
1919 // Since the Length class cannot use length variables
1920 // we must not create an InsetMathSpace.
1921 cell->push_back(MathAtom(new InsetMathMacro(buf, name)));
1923 mathed_parse_cell(ar, '{' + arg + '}', mode_);
1928 else if (t.cs() == "smash") {
1930 if (nextToken().asInput() == "[") {
1931 // Since the phantom inset cannot handle optional arguments
1932 // other than b and t, we must not create an InsetMathPhantom
1933 // if opt is different from b and t (bug 8967).
1934 docstring const opt = parse_verbatim_option();
1935 if (opt == "t" || opt == "b") {
1936 cell->push_back(createInsetMath(t.cs() + opt, buf));
1937 parse(cell->back().nucleus()->cell(0), FLAG_ITEM, mode);
1939 docstring const arg = parse_verbatim_item();
1940 cell->push_back(MathAtom(new InsetMathMacro(buf, t.cs())));
1942 mathed_parse_cell(ar, '[' + opt + ']', mode_);
1945 mathed_parse_cell(ar, '{' + arg + '}', mode_);
1950 cell->push_back(createInsetMath(t.cs(), buf));
1951 parse(cell->back().nucleus()->cell(0), FLAG_ITEM, mode);
1956 else if (t.cs() == "infer") {
1958 parse(ar, FLAG_OPTION, mode);
1959 cell->push_back(createInsetMath(t.cs(), buf));
1960 parse2(cell->back(), FLAG_ITEM, mode, false);
1964 else if (t.cs() == "lyxmathsym") {
1966 if (getToken().cat() != catBegin) {
1967 error("'{' expected in \\" + t.cs());
1972 CatCode cat = nextToken().cat();
1973 while (good() && (count || cat != catEnd)) {
1974 if (cat == catBegin)
1976 else if (cat == catEnd)
1978 cmd += getToken().asInput();
1979 cat = nextToken().cat();
1981 if (getToken().cat() != catEnd) {
1982 error("'}' expected in \\" + t.cs());
1988 cmd = Encodings::fromLaTeXCommand(cmd,
1989 Encodings::MATH_CMD | Encodings::TEXT_CMD,
1991 for (size_t i = 0; i < cmd.size(); ++i)
1992 cell->push_back(MathAtom(new InsetMathChar(cmd[i])));
1994 char_type c = rem[0];
1995 cell->push_back(MathAtom(new InsetMathChar(c)));
1996 cmd = rem.substr(1);
2000 } while (!cmd.empty());
2003 else if (!t.cs().empty()) {
2004 bool const no_mhchem =
2005 (t.cs() == "ce" || t.cs() == "cf")
2006 && buf && buf->params().use_package("mhchem") ==
2007 BufferParams::package_off;
2009 bool const is_user_macro = no_mhchem ||
2010 (buf && (mode_ & Parse::TRACKMACRO
2011 ? buf->usermacros.count(t.cs()) != 0
2012 : buf->getMacro(t.cs(), false) != 0));
2014 latexkeys const * l = in_word_set(t.cs());
2015 if (l && !is_user_macro) {
2016 if (l->inset == "big") {
2018 docstring const delim = getToken().asInput();
2019 if (InsetMathBig::isBigInsetDelim(delim))
2020 cell->push_back(MathAtom(
2021 new InsetMathBig(t.cs(), delim)));
2023 cell->push_back(createInsetMath(t.cs(), buf));
2024 // For some reason delim.empty()
2025 // is always false here
2031 else if (l->inset == "font") {
2032 cell->push_back(createInsetMath(t.cs(), buf));
2033 parse(cell->back().nucleus()->cell(0),
2034 FLAG_ITEM, asMode(mode, l->extra));
2037 else if (l->inset == "oldfont") {
2038 cell->push_back(createInsetMath(t.cs(), buf));
2039 parse(cell->back().nucleus()->cell(0),
2040 flags | FLAG_ALIGN, asMode(mode, l->extra));
2041 if (prevToken().cat() != catAlign &&
2042 prevToken().cs() != "\\")
2047 else if (l->inset == "style") {
2048 cell->push_back(createInsetMath(t.cs(), buf));
2049 parse(cell->back().nucleus()->cell(0),
2050 flags | FLAG_ALIGN, mode);
2051 if (prevToken().cat() != catAlign &&
2052 prevToken().cs() != "\\")
2057 else if (l->inset == "underset" || l->inset == "overset") {
2058 cell->push_back(createInsetMath(t.cs(), buf));
2059 parse(cell->back().nucleus()->cell(1), FLAG_ITEM, mode);
2060 parse(cell->back().nucleus()->cell(0), FLAG_ITEM, mode);
2064 MathAtom at = createInsetMath(t.cs(), buf);
2065 for (InsetMath::idx_type i = 0; i < at->nargs(); ++i)
2066 parse(at.nucleus()->cell(i),
2067 FLAG_ITEM, asMode(mode, l->extra));
2068 cell->push_back(at);
2073 bool is_unicode_symbol = false;
2074 if (mode == InsetMath::TEXT_MODE && !is_user_macro) {
2076 docstring cmd = prevToken().asInput();
2077 CatCode cat = nextToken().cat();
2078 if (cat == catBegin) {
2080 while (good() && (count || cat != catEnd)) {
2081 cat = nextToken().cat();
2082 cmd += getToken().asInput();
2084 if (cat == catBegin)
2086 else if (cat == catEnd)
2092 char_type c = Encodings::fromLaTeXCommand(cmd,
2093 Encodings::MATH_CMD | Encodings::TEXT_CMD,
2094 is_combining, termination);
2096 if (cat == catLetter)
2098 cmd += getToken().asInput();
2100 if (cat == catLetter)
2102 c = Encodings::fromLaTeXCommand(cmd,
2103 Encodings::MATH_CMD | Encodings::TEXT_CMD,
2104 is_combining, termination);
2108 if (nextToken().cat() == catBegin) {
2110 if (nextToken().cat() == catEnd) {
2116 while (nextToken().cat() == catSpace) {
2122 is_unicode_symbol = true;
2123 cell->push_back(MathAtom(new InsetMathChar(c)));
2125 while (num_tokens--)
2129 if (!is_unicode_symbol) {
2130 MathAtom at = is_user_macro ?
2131 MathAtom(new InsetMathMacro(buf, t.cs()))
2132 : createInsetMath(t.cs(), buf);
2133 InsetMath::mode_type m = mode;
2134 //if (m == InsetMath::UNDECIDED_MODE)
2135 //lyxerr << "default creation: m1: " << m << endl;
2136 if (at->currentMode() != InsetMath::UNDECIDED_MODE)
2137 m = at->currentMode();
2138 //lyxerr << "default creation: m2: " << m << endl;
2139 InsetMath::idx_type start = 0;
2140 // this fails on \bigg[...\bigg]
2142 //parse(opt, FLAG_OPTION, InsetMath::VERBATIM_MODE);
2143 //if (!opt.empty()) {
2145 // at.nucleus()->cell(0) = opt;
2147 for (InsetMath::idx_type i = start; i < at->nargs(); ++i) {
2148 parse(at.nucleus()->cell(i), FLAG_ITEM, m);
2149 if (mode == InsetMath::MATH_MODE)
2152 cell->push_back(at);
2158 if (flags & FLAG_LEAVE) {
2159 flags &= ~FLAG_LEAVE;
2168 } // anonymous namespace
2171 // FIXME This will likely need some work.
2172 char const * latexkeys::MathMLtype() const
2174 if (extra == "mathord")
2180 bool mathed_parse_cell(MathData & ar, docstring const & str, Parse::flags f)
2182 return Parser(str, f, ar.buffer()).parse(ar, 0, f & Parse::TEXTMODE ?
2183 InsetMath::TEXT_MODE : InsetMath::MATH_MODE);
2187 bool mathed_parse_cell(MathData & ar, istream & is, Parse::flags f)
2189 return Parser(is, f, ar.buffer()).parse(ar, 0, f & Parse::TEXTMODE ?
2190 InsetMath::TEXT_MODE : InsetMath::MATH_MODE);
2194 bool mathed_parse_normal(Buffer * buf, MathAtom & t, docstring const & str,
2197 return Parser(str, f, buf).parse(t);
2201 bool mathed_parse_normal(Buffer * buf, MathAtom & t, Lexer & lex,
2204 return Parser(lex, f, buf).parse(t);
2208 bool mathed_parse_normal(InsetMathGrid & grid, docstring const & str,
2211 return Parser(str, f, &grid.buffer()).parse1(grid, 0, f & Parse::TEXTMODE ?
2212 InsetMath::TEXT_MODE : InsetMath::MATH_MODE, false);
2218 fill(theCatcode, theCatcode + 128, catOther);
2219 fill(theCatcode + 'a', theCatcode + 'z' + 1, catLetter);
2220 fill(theCatcode + 'A', theCatcode + 'Z' + 1, catLetter);
2222 theCatcode[int('\\')] = catEscape;
2223 theCatcode[int('{')] = catBegin;
2224 theCatcode[int('}')] = catEnd;
2225 theCatcode[int('$')] = catMath;
2226 theCatcode[int('&')] = catAlign;
2227 theCatcode[int('\n')] = catNewline;
2228 theCatcode[int('#')] = catParameter;
2229 theCatcode[int('^')] = catSuper;
2230 theCatcode[int('_')] = catSub;
2231 theCatcode[int(0x7f)] = catIgnore;
2232 theCatcode[int(' ')] = catSpace;
2233 theCatcode[int('\t')] = catSpace;
2234 theCatcode[int('\r')] = catNewline;
2235 theCatcode[int('~')] = catActive;
2236 theCatcode[int('%')] = catComment;