3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
8 * Full author contact details are available in file CREDITS.
13 If someone desperately needs partial "structures" (such as a few
14 cells of an array inset or similar) (s)he could uses the
15 following hack as starting point to write some macros:
20 \def\makeamptab{\catcode`\&=4\relax}
21 \def\makeampletter{\catcode`\&=11\relax}
22 \def\b{\makeampletter\expandafter\makeamptab\bi}
40 #include "MathParser.h"
42 #include "InsetMathArray.h"
43 #include "InsetMathBig.h"
44 #include "InsetMathBrace.h"
45 #include "InsetMathCancelto.h"
46 #include "InsetMathChar.h"
47 #include "InsetMathColor.h"
48 #include "InsetMathComment.h"
49 #include "InsetMathDelim.h"
50 #include "InsetMathEnsureMath.h"
51 #include "InsetMathEnv.h"
52 #include "InsetMathFrac.h"
53 #include "InsetMathKern.h"
54 #include "MathMacro.h"
55 #include "InsetMathPar.h"
56 #include "InsetMathRef.h"
57 #include "InsetMathRoot.h"
58 #include "InsetMathScript.h"
59 #include "InsetMathSpace.h"
60 #include "InsetMathSplit.h"
61 #include "InsetMathSqrt.h"
62 #include "InsetMathStackrel.h"
63 #include "InsetMathString.h"
64 #include "InsetMathTabular.h"
65 #include "MathMacroTemplate.h"
66 #include "MathFactory.h"
67 #include "MathMacroArgument.h"
68 #include "MathSupport.h"
71 #include "BufferParams.h"
75 #include "support/debug.h"
76 #include "support/convert.h"
77 #include "support/docstream.h"
89 InsetMath::mode_type asMode(InsetMath::mode_type oldmode, docstring const & str)
91 //lyxerr << "handling mode: '" << str << "'" << endl;
92 if (str == "mathmode")
93 return InsetMath::MATH_MODE;
94 if (str == "textmode" || str == "forcetext")
95 return InsetMath::TEXT_MODE;
100 bool stared(docstring const & s)
102 size_t const n = s.size();
103 return n && s[n - 1] == '*';
107 docstring const repl(docstring const & oldstr, char_type const c,
108 docstring const & macro, bool textmode = false)
114 for (i = 0, j = 0; i < oldstr.size(); ++i) {
115 if (c == oldstr[i]) {
116 newstr.append(oldstr, j, i - j);
117 newstr.append(macro);
119 if (macro.size() > 2 && j < oldstr.size())
120 newstr += (textmode && oldstr[j] == ' ' ? '\\' : ' ');
128 newstr.append(oldstr, j, i - j);
133 docstring escapeSpecialChars(docstring const & str, bool textmode)
135 docstring const backslash = textmode ? from_ascii("\\textbackslash")
136 : from_ascii("\\backslash");
137 docstring const caret = textmode ? from_ascii("\\textasciicircum")
138 : from_ascii("\\mathcircumflex");
139 docstring const tilde = textmode ? from_ascii("\\textasciitilde")
140 : from_ascii("\\sim");
142 return repl(repl(repl(repl(repl(repl(repl(repl(repl(repl(str,
143 '\\', backslash, textmode),
144 '^', caret, textmode),
145 '~', tilde, textmode),
146 '_', from_ascii("\\_")),
147 '$', from_ascii("\\$")),
148 '#', from_ascii("\\#")),
149 '&', from_ascii("\\&")),
150 '%', from_ascii("\\%")),
151 '{', from_ascii("\\{")),
152 '}', from_ascii("\\}"));
157 * Add the row \p cellrow to \p grid.
158 * \returns wether the row could be added. Adding a row can fail for
159 * environments like "equation" that have a fixed number of rows.
161 bool addRow(InsetMathGrid & grid, InsetMathGrid::row_type & cellrow,
162 docstring const & vskip, bool allow_newpage_ = true)
165 if (cellrow == grid.nrows()) {
166 //lyxerr << "adding row " << cellrow << endl;
167 grid.addRow(cellrow - 1);
168 if (cellrow == grid.nrows()) {
169 // We can't add a row to this grid, so let's
170 // append the content of this cell to the previous
172 // This does not happen in well formed .lyx files,
173 // but LyX versions 1.3.x and older could create
174 // such files and tex2lyx can still do that.
176 lyxerr << "ignoring extra row";
178 lyxerr << " with extra space " << to_utf8(vskip);
180 lyxerr << " with no page break allowed";
181 lyxerr << '.' << endl;
185 grid.vcrskip(Length(to_utf8(vskip)), cellrow - 1);
186 grid.rowinfo(cellrow - 1).allow_newpage_ = allow_newpage_;
192 * Add the column \p cellcol to \p grid.
193 * \returns wether the column could be added. Adding a column can fail for
194 * environments like "eqnarray" that have a fixed number of columns.
196 bool addCol(InsetMathGrid & grid, InsetMathGrid::col_type & cellcol)
199 if (cellcol == grid.ncols()) {
200 //lyxerr << "adding column " << cellcol << endl;
201 grid.addCol(cellcol);
202 if (cellcol == grid.ncols()) {
203 // We can't add a column to this grid, so let's
204 // append the content of this cell to the previous
206 // This does not happen in well formed .lyx files,
207 // but LyX versions 1.3.x and older could create
208 // such files and tex2lyx can still do that.
210 lyxerr << "ignoring extra column." << endl;
219 * Check whether the last row is empty and remove it if yes.
220 * Otherwise the following code
228 * will result in a grid with 3 rows (+ the dummy row that is always present),
229 * because the last '\\' opens a new row.
230 * Note that this is only needed for inner-hull grid types, such as array
231 * or aligned, but not for outer-hull grid types, such as eqnarray or align.
233 void delEmptyLastRow(InsetMathGrid & grid)
235 InsetMathGrid::row_type const row = grid.nrows() - 1;
236 for (InsetMathGrid::col_type col = 0; col < grid.ncols(); ++col) {
237 if (!grid.cell(grid.index(row, col)).empty())
240 // Copy the row information of the empty row (which would contain the
241 // last hline in the example above) to the dummy row and delete the
243 grid.rowinfo(row + 1) = grid.rowinfo(row);
249 * Tell whether the environment name corresponds to an inner-hull grid type.
251 bool innerHull(docstring const & name)
253 // For [bB]matrix, [vV]matrix, and pmatrix we can check the suffix only
254 return name == "array" || name == "cases" || name == "aligned"
255 || name == "alignedat" || name == "gathered" || name == "split"
256 || name == "subarray" || name == "tabular" || name == "matrix"
257 || name == "smallmatrix" || name.substr(1) == "matrix";
261 // These are TeX's catcodes
263 catEscape, // 0 backslash
273 catSpace, // 10 space
274 catLetter, // 11 a-zA-Z
275 catOther, // 12 none of the above
278 catInvalid // 15 <delete>
281 CatCode theCatcode[128];
284 inline CatCode catcode(char_type c)
286 /* The only characters that are not catOther lie in the pure ASCII
287 * range. Therefore theCatcode has only 128 entries.
288 * TeX itself deals with 8bit characters, so if needed this table
289 * could be enlarged to 256 entries.
290 * Any larger value does not make sense, since the fact that we use
291 * unicode internally does not change Knuth's TeX engine.
292 * Apart from that a table for the full 21bit UCS4 range would waste
293 * too much memory. */
297 return theCatcode[c];
302 FLAG_ALIGN = 1 << 0, // next & or \\ ends the parsing process
303 FLAG_BRACE_LAST = 1 << 1, // next closing brace ends the parsing
304 FLAG_RIGHT = 1 << 2, // next \\right ends the parsing process
305 FLAG_END = 1 << 3, // next \\end ends the parsing process
306 FLAG_BRACK_LAST = 1 << 4, // next closing bracket ends the parsing
307 FLAG_TEXTMODE = 1 << 5, // we are in a box
308 FLAG_ITEM = 1 << 6, // read a (possibly braced) token
309 FLAG_LEAVE = 1 << 7, // leave the loop at the end
310 FLAG_SIMPLE = 1 << 8, // next $ leaves the loop
311 FLAG_EQUATION = 1 << 9, // next \] leaves the loop
312 FLAG_SIMPLE2 = 1 << 10, // next \) leaves the loop
313 FLAG_OPTION = 1 << 11, // read [...] style option
314 FLAG_BRACED = 1 << 12 // read {...} style argument
319 // Helper class for parsing
325 Token() : cs_(), char_(0), cat_(catIgnore) {}
327 Token(char_type c, CatCode cat) : cs_(), char_(c), cat_(cat) {}
329 explicit Token(docstring const & cs) : cs_(cs), char_(0), cat_(catIgnore) {}
332 docstring const & cs() const { return cs_; }
334 CatCode cat() const { return cat_; }
336 char_type character() const { return char_; }
338 docstring asString() const { return !cs_.empty() ? cs_ : docstring(1, char_); }
340 docstring asInput() const { return !cs_.empty() ? '\\' + cs_ : docstring(1, char_); }
352 ostream & operator<<(ostream & os, Token const & t)
354 if (!t.cs().empty()) {
355 docstring const & cs = t.cs();
356 // FIXME: For some strange reason, the stream operator instanciate
357 // a new Token before outputting the contents of t.cs().
358 // Because of this the line
360 // below becomes recursive.
361 // In order to avoid that we return early:
364 os << '\\' << to_utf8(cs);
366 else if (t.cat() == catLetter)
369 os << '[' << t.character() << ',' << t.cat() << ']';
377 typedef InsetMath::mode_type mode_type;
379 typedef Parse::flags parse_mode;
382 Parser(Lexer & lex, parse_mode mode, Buffer * buf);
383 /// Only use this for reading from .lyx file format, for the reason
384 /// see Parser::tokenize(istream &).
385 Parser(istream & is, parse_mode mode, Buffer * buf);
387 Parser(docstring const & str, parse_mode mode, Buffer * buf);
390 bool parse(MathAtom & at);
392 bool parse(MathData & array, unsigned flags, mode_type mode);
394 bool parse1(InsetMathGrid & grid, unsigned flags, mode_type mode,
397 MathData parse(unsigned flags, mode_type mode);
399 int lineno() const { return lineno_; }
405 void parse2(MathAtom & at, unsigned flags, mode_type mode, bool numbered);
406 /// get arg delimited by 'left' and 'right'
407 docstring getArg(char_type left, char_type right);
411 void error(string const & msg);
412 void error(docstring const & msg) { error(to_utf8(msg)); }
413 /// dump contents to screen
415 /// Only use this for reading from .lyx file format (see
416 /// implementation for reason)
417 void tokenize(istream & is);
419 void tokenize(docstring const & s);
421 void skipSpaceTokens(idocstream & is, char_type c);
423 void push_back(Token const & t);
427 Token const & prevToken() const;
429 Token const & nextToken() const;
431 Token const & getToken();
432 /// skips spaces if any
435 void lex(docstring const & s);
439 docstring parse_verbatim_item();
441 docstring parse_verbatim_option();
446 vector<Token> tokens_;
449 /// Stack of active environments
450 vector<docstring> environments_;
460 Parser::Parser(Lexer & lexer, parse_mode mode, Buffer * buf)
461 : lineno_(lexer.lineNumber()), pos_(0), mode_(mode), success_(true),
464 tokenize(lexer.getStream());
469 Parser::Parser(istream & is, parse_mode mode, Buffer * buf)
470 : lineno_(0), pos_(0), mode_(mode), success_(true), buffer_(buf)
476 Parser::Parser(docstring const & str, parse_mode mode, Buffer * buf)
477 : lineno_(0), pos_(0), mode_(mode), success_(true), buffer_(buf)
483 void Parser::push_back(Token const & t)
485 tokens_.push_back(t);
489 void Parser::pop_back()
495 Token const & Parser::prevToken() const
497 static const Token dummy;
498 return pos_ > 0 ? tokens_[pos_ - 1] : dummy;
502 Token const & Parser::nextToken() const
504 static const Token dummy;
505 return good() ? tokens_[pos_] : dummy;
509 Token const & Parser::getToken()
511 static const Token dummy;
512 //lyxerr << "looking at token " << tokens_[pos_] << " pos: " << pos_ << endl;
513 return good() ? tokens_[pos_++] : dummy;
517 void Parser::skipSpaces()
519 while (nextToken().cat() == catSpace || nextToken().cat() == catNewline)
524 void Parser::putback()
530 bool Parser::good() const
532 return pos_ < tokens_.size();
536 char_type Parser::getChar()
539 error("The input stream is not well...");
542 return tokens_[pos_++].character();
546 docstring Parser::getArg(char_type left, char_type right)
554 char_type c = getChar();
559 while ((c = getChar()) != right && good())
566 void Parser::skipSpaceTokens(idocstream & is, char_type c)
568 // skip trailing spaces
569 while (catcode(c) == catSpace || catcode(c) == catNewline)
572 //lyxerr << "putting back: " << c << endl;
577 void Parser::tokenize(istream & is)
579 // eat everything up to the next \end_inset or end of stream
580 // and store it in s for further tokenization
585 if (s.size() >= 10 && s.substr(s.size() - 10) == "\\end_inset") {
586 s = s.substr(0, s.size() - 10);
590 // Remove the space after \end_inset
591 if (is.get(c) && c != ' ')
595 tokenize(from_utf8(s));
599 void Parser::tokenize(docstring const & buffer)
601 idocstringstream is(mode_ & Parse::VERBATIM
602 ? escapeSpecialChars(buffer, mode_ & Parse::TEXTMODE)
603 : buffer, ios::in | ios::binary);
607 //lyxerr << "reading c: " << c << endl;
609 switch (catcode(c)) {
613 if (catcode(c) == catNewline)
614 ; //push_back(Token("par"));
616 push_back(Token('\n', catNewline));
624 while (is.get(c) && catcode(c) != catNewline)
634 error("unexpected end of input");
639 if (catcode(c) == catLetter) {
641 while (is.get(c) && catcode(c) == catLetter)
643 skipSpaceTokens(is, c);
652 push_back(Token(c, catcode(c)));
654 skipSpaceTokens(is, c);
659 if (!(mode_ & Parse::QUIET))
660 lyxerr << "ignoring a char: " << int(c) << endl;
665 push_back(Token(c, catcode(c)));
675 void Parser::dump() const
677 lyxerr << "\nTokens: ";
678 for (unsigned i = 0; i < tokens_.size(); ++i) {
681 lyxerr << tokens_[i];
683 lyxerr << " pos: " << pos_ << endl;
687 void Parser::error(string const & msg)
690 if (!(mode_ & Parse::QUIET)) {
691 lyxerr << "Line ~" << lineno_ << ": Math parse error: "
698 bool Parser::parse(MathAtom & at)
701 MathData ar(buffer_);
702 parse(ar, false, InsetMath::UNDECIDED_MODE);
703 if (ar.size() != 1 || ar.front()->getType() == hullNone) {
704 if (!(mode_ & Parse::QUIET))
705 lyxerr << "unusual contents found: " << ar << endl;
706 at = MathAtom(new InsetMathPar(buffer_, ar));
707 //if (at->nargs() > 0)
708 // at.nucleus()->cell(0) = ar;
710 // lyxerr << "unusual contents found: " << ar << endl;
718 docstring Parser::parse_verbatim_option()
722 if (nextToken().character() == '[') {
723 Token t = getToken();
724 for (Token t = getToken(); t.character() != ']' && good(); t = getToken()) {
725 if (t.cat() == catBegin) {
727 res += '{' + parse_verbatim_item() + '}';
736 docstring Parser::parse_verbatim_item()
740 if (nextToken().cat() == catBegin) {
741 Token t = getToken();
742 for (Token t = getToken(); t.cat() != catEnd && good(); t = getToken()) {
743 if (t.cat() == catBegin) {
745 res += '{' + parse_verbatim_item() + '}';
755 MathData Parser::parse(unsigned flags, mode_type mode)
757 MathData ar(buffer_);
758 parse(ar, flags, mode);
763 bool Parser::parse(MathData & array, unsigned flags, mode_type mode)
765 InsetMathGrid grid(buffer_, 1, 1);
766 parse1(grid, flags, mode, false);
767 array = grid.cell(0);
772 void Parser::parse2(MathAtom & at, const unsigned flags, const mode_type mode,
775 parse1(*(at.nucleus()->asGridInset()), flags, mode, numbered);
779 bool Parser::parse1(InsetMathGrid & grid, unsigned flags,
780 const mode_type mode, const bool numbered)
783 InsetMathGrid::row_type cellrow = 0;
784 InsetMathGrid::col_type cellcol = 0;
785 MathData * cell = &grid.cell(grid.index(cellrow, cellcol));
786 Buffer * buf = buffer_;
788 if (grid.asHullInset())
789 grid.asHullInset()->numbered(cellrow, numbered);
792 //lyxerr << " flags: " << flags << endl;
793 //lyxerr << " mode: " << mode << endl;
794 //lyxerr << "grid: " << grid << endl;
797 Token const & t = getToken();
800 lyxerr << "t: " << t << " flags: " << flags << endl;
801 lyxerr << "mode: " << mode << endl;
806 if (flags & FLAG_ITEM) {
808 if (t.cat() == catBegin) {
809 // skip the brace and collect everything to the next matching
811 parse1(grid, FLAG_BRACE_LAST, mode, numbered);
815 // handle only this single token, leave the loop if done
820 if (flags & FLAG_BRACED) {
821 if (t.cat() == catSpace)
824 if (t.cat() != catBegin) {
825 error("opening brace expected");
829 // skip the brace and collect everything to the next matching
831 flags = FLAG_BRACE_LAST;
835 if (flags & FLAG_OPTION) {
836 if (t.cat() == catOther && t.character() == '[') {
838 parse(ar, FLAG_BRACK_LAST, mode);
841 // no option found, put back token and we are done
850 if (t.cat() == catMath) {
851 if (mode != InsetMath::MATH_MODE) {
852 // we are inside some text mode thingy, so opening new math is allowed
853 Token const & n = getToken();
854 if (n.cat() == catMath) {
855 // TeX's $$...$$ syntax for displayed math
856 if (mode == InsetMath::UNDECIDED_MODE) {
857 cell->push_back(MathAtom(new InsetMathHull(buf, hullEquation)));
858 parse2(cell->back(), FLAG_SIMPLE, InsetMath::MATH_MODE, false);
859 getToken(); // skip the second '$' token
861 // This is not an outer hull and display math is
862 // not allowed inside text mode environments.
863 error("bad math environment");
867 // simple $...$ stuff
869 if (mode == InsetMath::UNDECIDED_MODE) {
870 cell->push_back(MathAtom(new InsetMathHull(buf, hullSimple)));
871 parse2(cell->back(), FLAG_SIMPLE, InsetMath::MATH_MODE, false);
873 // Don't create nested math hulls (bug #5392)
874 cell->push_back(MathAtom(new InsetMathEnsureMath(buf)));
875 parse(cell->back().nucleus()->cell(0), FLAG_SIMPLE, InsetMath::MATH_MODE);
880 else if (flags & FLAG_SIMPLE) {
881 // this is the end of the formula
886 Token const & n = getToken();
887 if (n.cat() == catMath) {
888 error("something strange in the parser");
891 // This is inline math ($...$), but the parser thinks we are
892 // already in math mode and latex would issue an error, unless we
893 // are inside a text mode user macro. We have no way to tell, so
894 // let's play safe by using \ensuremath, as it will work in any case.
896 cell->push_back(MathAtom(new InsetMathEnsureMath(buf)));
897 parse(cell->back().nucleus()->cell(0), FLAG_SIMPLE, InsetMath::MATH_MODE);
902 else if (t.cat() == catLetter)
903 cell->push_back(MathAtom(new InsetMathChar(t.character())));
905 else if (t.cat() == catSpace && mode != InsetMath::MATH_MODE) {
906 if (cell->empty() || cell->back()->getChar() != ' ')
907 cell->push_back(MathAtom(new InsetMathChar(t.character())));
910 else if (t.cat() == catNewline && mode != InsetMath::MATH_MODE) {
911 if (cell->empty() || cell->back()->getChar() != ' ')
912 cell->push_back(MathAtom(new InsetMathChar(' ')));
915 else if (t.cat() == catParameter) {
916 Token const & n = getToken();
917 cell->push_back(MathAtom(new MathMacroArgument(n.character()-'0')));
920 else if (t.cat() == catActive)
921 cell->push_back(MathAtom(new InsetMathSpace(string(1, t.character()), "")));
923 else if (t.cat() == catBegin) {
925 parse(ar, FLAG_BRACE_LAST, mode);
926 // do not create a BraceInset if they were written by LyX
927 // this helps to keep the annoyance of "a choose b" to a minimum
928 if (ar.size() == 1 && ar[0]->extraBraces())
931 cell->push_back(MathAtom(new InsetMathBrace(ar)));
934 else if (t.cat() == catEnd) {
935 if (flags & FLAG_BRACE_LAST)
937 error("found '}' unexpectedly");
938 //LASSERT(false, /**/);
939 //add(cell, '}', LM_TC_TEX);
942 else if (t.cat() == catAlign) {
943 //lyxerr << " column now " << (cellcol + 1)
944 // << " max: " << grid.ncols() << endl;
945 if (flags & FLAG_ALIGN)
947 if (addCol(grid, cellcol))
948 cell = &grid.cell(grid.index(cellrow, cellcol));
951 else if (t.cat() == catSuper || t.cat() == catSub) {
952 bool up = (t.cat() == catSuper);
953 // we need no new script inset if the last thing was a scriptinset,
954 // which has that script already not the same script already
956 cell->push_back(MathAtom(new InsetMathScript(buf, up)));
957 else if (cell->back()->asScriptInset() &&
958 !cell->back()->asScriptInset()->has(up))
959 cell->back().nucleus()->asScriptInset()->ensure(up);
960 else if (cell->back()->asScriptInset())
961 cell->push_back(MathAtom(new InsetMathScript(buf, up)));
963 cell->back() = MathAtom(new InsetMathScript(buf, cell->back(), up));
964 InsetMathScript * p = cell->back().nucleus()->asScriptInset();
965 // special handling of {}-bases
966 // Here we could remove the brace inset for things
967 // like {a'}^2 and add the braces back in
968 // InsetMathScript::write().
969 // We do not do it, since it is not possible to detect
970 // reliably whether the braces are needed because the
971 // nucleus contains more than one symbol, or whether
972 // they are needed for unknown commands like \xx{a}_0
973 // or \yy{a}{b}_0. This was done in revision 14819
974 // in an unreliable way. See this thread
975 // http://www.mail-archive.com/lyx-devel%40lists.lyx.org/msg104917.html
977 // However, we remove empty braces because they look
978 // ugly on screen and we are sure that they were added
979 // by the write() method (and will be re-added on save).
980 if (p->nuc().size() == 1 &&
981 p->nuc().back()->asBraceInset() &&
982 p->nuc().back()->asBraceInset()->cell(0).empty())
985 parse(p->cell(p->idxOfScript(up)), FLAG_ITEM, mode);
992 else if (t.character() == ']' && (flags & FLAG_BRACK_LAST)) {
993 //lyxerr << "finished reading option" << endl;
997 else if (t.cat() == catOther) {
998 char_type c = t.character();
999 if (isAsciiOrMathAlpha(c)
1000 || mode_ & Parse::VERBATIM
1001 || !(mode_ & Parse::USETEXT)
1002 || mode == InsetMath::TEXT_MODE) {
1003 cell->push_back(MathAtom(new InsetMathChar(c)));
1005 MathAtom at = createInsetMath("text", buf);
1006 at.nucleus()->cell(0).push_back(MathAtom(new InsetMathChar(c)));
1007 while (nextToken().cat() == catOther
1008 && !isAsciiOrMathAlpha(nextToken().character())) {
1009 c = getToken().character();
1010 at.nucleus()->cell(0).push_back(MathAtom(new InsetMathChar(c)));
1012 cell->push_back(at);
1016 else if (t.cat() == catComment) {
1019 Token const & t = getToken();
1020 if (t.cat() == catNewline)
1024 cell->push_back(MathAtom(new InsetMathComment(buf, s)));
1029 // control sequences
1032 else if (t.cs() == "lyxlock") {
1034 cell->back().nucleus()->lock(true);
1037 else if ((t.cs() == "global" && nextToken().cs() == "def") ||
1039 if (t.cs() == "global")
1043 docstring name = getToken().cs();
1048 while (good() && nextToken().cat() != catBegin) {
1049 pars += getToken().cs();
1056 parse(def, FLAG_ITEM, InsetMath::UNDECIDED_MODE);
1058 // is a version for display attached?
1061 if (nextToken().cat() == catBegin)
1062 parse(display, FLAG_ITEM, InsetMath::MATH_MODE);
1064 cell->push_back(MathAtom(new MathMacroTemplate(buf,
1065 name, nargs, 0, MacroTypeDef,
1066 vector<MathData>(), def, display)));
1068 if (buf && (mode_ & Parse::TRACKMACRO))
1069 buf->usermacros.insert(name);
1072 else if (t.cs() == "newcommand" ||
1073 t.cs() == "renewcommand" ||
1074 t.cs() == "newlyxcommand") {
1076 if (getToken().cat() != catBegin) {
1077 error("'{' in \\newcommand expected (1) ");
1080 docstring name = getToken().cs();
1081 if (getToken().cat() != catEnd) {
1082 error("'}' in \\newcommand expected");
1087 docstring const arg = getArg('[', ']');
1090 nargs = convert<int>(arg);
1092 // optional argument given?
1095 vector<MathData> optionalValues;
1096 while (nextToken().character() == '[') {
1098 optionalValues.push_back(MathData());
1099 parse(optionalValues[optionals], FLAG_BRACK_LAST, mode);
1104 parse(def, FLAG_ITEM, InsetMath::UNDECIDED_MODE);
1106 // is a version for display attached?
1109 if (nextToken().cat() == catBegin)
1110 parse(display, FLAG_ITEM, InsetMath::MATH_MODE);
1112 cell->push_back(MathAtom(new MathMacroTemplate(buf,
1113 name, nargs, optionals, MacroTypeNewcommand,
1114 optionalValues, def, display)));
1116 if (buf && (mode_ & Parse::TRACKMACRO))
1117 buf->usermacros.insert(name);
1120 else if (t.cs() == "newcommandx" ||
1121 t.cs() == "renewcommandx") {
1122 // \newcommandx{\foo}[2][usedefault, addprefix=\global,1=default]{#1,#2}
1125 if (nextToken().cat() == catBegin) {
1127 name = getToken().cs();
1128 if (getToken().cat() != catEnd) {
1129 error("'}' in \\newcommandx expected");
1133 name = getToken().cs();
1136 docstring const arg = getArg('[', ']');
1138 error("[num] in \\newcommandx expected");
1141 int nargs = convert<int>(arg);
1145 vector<MathData> optionalValues;
1146 if (nextToken().character() == '[') {
1150 // handle 'opt=value' options, separated by ','.
1152 while (nextToken().character() != ']' && good()) {
1153 if (nextToken().character() >= '1'
1154 && nextToken().character() <= '9') {
1155 // optional value -> get parameter number
1156 int n = getChar() - '0';
1158 error("Arity of \\newcommandx too low "
1159 "for given optional parameter.");
1164 if (getToken().character() != '=') {
1165 error("'=' and optional parameter value "
1166 "expected for \\newcommandx");
1171 int optNum = max(size_t(n), optionalValues.size());
1172 optionalValues.resize(optNum);
1173 optionalValues[n - 1].clear();
1174 while (nextToken().character() != ']'
1175 && nextToken().character() != ',') {
1177 parse(data, FLAG_ITEM, InsetMath::UNDECIDED_MODE);
1178 optionalValues[n - 1].append(data);
1180 optionals = max(n, optionals);
1181 } else if (nextToken().cat() == catLetter) {
1182 // we in fact ignore every non-optional
1187 while (nextToken().cat() == catLetter)
1193 if (nextToken().character() == '=') {
1195 while (nextToken().character() != ']'
1196 && nextToken().character() != ',')
1197 parse(value, FLAG_ITEM,
1198 InsetMath::UNDECIDED_MODE);
1201 error("option for \\newcommandx expected");
1207 if (nextToken().character() == ',') {
1210 } else if (nextToken().character() != ']') {
1211 error("Expecting ',' or ']' in options "
1212 "of \\newcommandx");
1225 parse(def, FLAG_ITEM, InsetMath::UNDECIDED_MODE);
1227 // is a version for display attached?
1230 if (nextToken().cat() == catBegin)
1231 parse(display, FLAG_ITEM, InsetMath::MATH_MODE);
1233 cell->push_back(MathAtom(new MathMacroTemplate(buf,
1234 name, nargs, optionals, MacroTypeNewcommandx,
1235 optionalValues, def, display)));
1237 if (buf && (mode_ & Parse::TRACKMACRO))
1238 buf->usermacros.insert(name);
1241 else if (t.cs() == "(") {
1242 cell->push_back(MathAtom(new InsetMathEnsureMath(buf)));
1243 parse(cell->back().nucleus()->cell(0), FLAG_SIMPLE2, InsetMath::MATH_MODE);
1246 else if (t.cs() == "[") {
1247 if (mode != InsetMath::UNDECIDED_MODE) {
1248 error("bad math environment");
1251 cell->push_back(MathAtom(new InsetMathHull(buf, hullEquation)));
1252 parse2(cell->back(), FLAG_EQUATION, InsetMath::MATH_MODE, false);
1255 else if (t.cs() == "protect")
1256 // ignore \\protect, will hopefully be re-added during output
1259 else if (t.cs() == "end") {
1260 if (flags & FLAG_END) {
1261 // eat environment name
1262 docstring const name = getArg('{', '}');
1263 if (environments_.empty())
1264 error("'found \\end{" + name +
1265 "}' without matching '\\begin{" +
1267 else if (name != environments_.back())
1268 error("'\\end{" + name +
1269 "}' does not match '\\begin{" +
1270 environments_.back() + "}'");
1272 environments_.pop_back();
1273 // Delete empty last row in matrix
1275 // If you abuse InsetMathGrid for
1276 // non-matrix like structures you
1277 // probably need to refine this test.
1278 // Right now we only have to test for
1279 // single line hull insets.
1280 if (grid.nrows() > 1 && innerHull(name))
1281 delEmptyLastRow(grid);
1285 error("found 'end' unexpectedly");
1288 else if (t.cs() == ")") {
1289 if (flags & FLAG_SIMPLE2)
1291 error("found '\\)' unexpectedly");
1294 else if (t.cs() == "]") {
1295 if (flags & FLAG_EQUATION)
1297 error("found '\\]' unexpectedly");
1300 else if (t.cs() == "\\") {
1301 if (flags & FLAG_ALIGN)
1304 if (nextToken().asInput() == "*") {
1306 added = addRow(grid, cellrow, docstring(), false);
1308 added = addRow(grid, cellrow, getArg('[', ']'));
1310 error("missing token after \\\\");
1313 if (grid.asHullInset())
1314 grid.asHullInset()->numbered(
1316 cell = &grid.cell(grid.index(cellrow,
1322 else if (t.cs() == "multicolumn") {
1323 // extract column count and insert dummy cells
1325 parse(count, FLAG_ITEM, mode);
1327 if (!extractNumber(count, cols)) {
1329 lyxerr << " can't extract number of cells from " << count << endl;
1331 // resize the table if necessary
1332 for (int i = 0; i < cols; ++i) {
1333 if (addCol(grid, cellcol)) {
1334 cell = &grid.cell(grid.index(
1336 // mark this as dummy
1337 grid.cellinfo(grid.index(
1338 cellrow, cellcol)).dummy_ = true;
1341 // the last cell is the real thing, not a dummy
1342 grid.cellinfo(grid.index(cellrow, cellcol)).dummy_ = false;
1344 // read special alignment
1346 parse(align, FLAG_ITEM, mode);
1347 //grid.cellinfo(grid.index(cellrow, cellcol)).align_ = extractString(align);
1349 // parse the remaining contents into the "real" cell
1350 parse(*cell, FLAG_ITEM, mode);
1354 else if (t.cs() == "limits" || t.cs() == "nolimits") {
1355 CatCode const cat = nextToken().cat();
1356 if (cat == catSuper || cat == catSub)
1357 limits = t.cs() == "limits" ? 1 : -1;
1359 MathAtom at = createInsetMath(t.cs(), buf);
1360 cell->push_back(at);
1364 else if (t.cs() == "nonumber") {
1365 if (grid.asHullInset())
1366 grid.asHullInset()->numbered(cellrow, false);
1369 else if (t.cs() == "number") {
1370 if (grid.asHullInset())
1371 grid.asHullInset()->numbered(cellrow, true);
1374 else if (t.cs() == "hline") {
1375 grid.rowinfo(cellrow).lines_ ++;
1378 else if (t.cs() == "sqrt") {
1380 parse(ar, FLAG_OPTION, mode);
1382 cell->push_back(MathAtom(new InsetMathRoot(buf)));
1383 cell->back().nucleus()->cell(0) = ar;
1384 parse(cell->back().nucleus()->cell(1), FLAG_ITEM, mode);
1386 cell->push_back(MathAtom(new InsetMathSqrt(buf)));
1387 parse(cell->back().nucleus()->cell(0), FLAG_ITEM, mode);
1391 else if (t.cs() == "cancelto") {
1393 parse(ar, FLAG_ITEM, mode);
1394 cell->push_back(MathAtom(new InsetMathCancelto(buf)));
1395 cell->back().nucleus()->cell(1) = ar;
1396 parse(cell->back().nucleus()->cell(0), FLAG_ITEM, mode);
1399 else if (t.cs() == "unit") {
1400 // Allowed formats \unit[val]{unit}
1402 parse(ar, FLAG_OPTION, mode);
1404 cell->push_back(MathAtom(new InsetMathFrac(buf, InsetMathFrac::UNIT)));
1405 cell->back().nucleus()->cell(0) = ar;
1406 parse(cell->back().nucleus()->cell(1), FLAG_ITEM, mode);
1408 cell->push_back(MathAtom(new InsetMathFrac(buf, InsetMathFrac::UNIT, 1)));
1409 parse(cell->back().nucleus()->cell(0), FLAG_ITEM, mode);
1413 else if (t.cs() == "unitfrac") {
1414 // Here allowed formats are \unitfrac[val]{num}{denom}
1416 parse(ar, FLAG_OPTION, mode);
1418 cell->push_back(MathAtom(new InsetMathFrac(buf, InsetMathFrac::UNITFRAC, 3)));
1419 cell->back().nucleus()->cell(2) = ar;
1421 cell->push_back(MathAtom(new InsetMathFrac(buf, InsetMathFrac::UNITFRAC)));
1423 parse(cell->back().nucleus()->cell(0), FLAG_ITEM, mode);
1424 parse(cell->back().nucleus()->cell(1), FLAG_ITEM, mode);
1427 else if (t.cs() == "cfrac") {
1428 // allowed formats are \cfrac[pos]{num}{denom}
1429 docstring const arg = getArg('[', ']');
1430 //lyxerr << "got so far: '" << arg << "'" << endl;
1432 cell->push_back(MathAtom(new InsetMathFrac(buf, InsetMathFrac::CFRACLEFT)));
1433 else if (arg == "r")
1434 cell->push_back(MathAtom(new InsetMathFrac(buf, InsetMathFrac::CFRACRIGHT)));
1435 else if (arg.empty() || arg == "c")
1436 cell->push_back(MathAtom(new InsetMathFrac(buf, InsetMathFrac::CFRAC)));
1438 error("found invalid optional argument");
1441 parse(cell->back().nucleus()->cell(0), FLAG_ITEM, mode);
1442 parse(cell->back().nucleus()->cell(1), FLAG_ITEM, mode);
1445 else if (t.cs() == "stackrel") {
1446 // Here allowed formats are \stackrel[subscript]{superscript}{operator}
1448 parse(ar, FLAG_OPTION, mode);
1449 cell->push_back(MathAtom(new InsetMathStackrel(buf, !ar.empty())));
1451 cell->back().nucleus()->cell(2) = ar;
1452 parse(cell->back().nucleus()->cell(0), FLAG_ITEM, mode);
1453 parse(cell->back().nucleus()->cell(1), FLAG_ITEM, mode);
1456 else if (t.cs() == "xrightarrow" || t.cs() == "xleftarrow") {
1457 cell->push_back(createInsetMath(t.cs(), buf));
1458 parse(cell->back().nucleus()->cell(1), FLAG_OPTION, mode);
1459 parse(cell->back().nucleus()->cell(0), FLAG_ITEM, mode);
1462 else if (t.cs() == "ref" || t.cs() == "eqref" || t.cs() == "prettyref"
1463 || t.cs() == "pageref" || t.cs() == "vpageref" || t.cs() == "vref") {
1464 cell->push_back(MathAtom(new InsetMathRef(buf, t.cs())));
1465 docstring const opt = parse_verbatim_option();
1466 docstring const ref = parse_verbatim_item();
1468 cell->back().nucleus()->cell(1).push_back(
1469 MathAtom(new InsetMathString(opt)));
1471 cell->back().nucleus()->cell(0).push_back(
1472 MathAtom(new InsetMathString(ref)));
1475 else if (t.cs() == "left") {
1477 Token const & tl = getToken();
1478 // \| and \Vert are equivalent, and InsetMathDelim
1480 // FIXME: fix this in InsetMathDelim itself!
1481 docstring const l = tl.cs() == "|" ? from_ascii("Vert") : tl.asString();
1483 parse(ar, FLAG_RIGHT, mode);
1487 Token const & tr = getToken();
1488 docstring const r = tr.cs() == "|" ? from_ascii("Vert") : tr.asString();
1489 cell->push_back(MathAtom(new InsetMathDelim(buf, l, r, ar)));
1492 else if (t.cs() == "right") {
1493 if (flags & FLAG_RIGHT)
1495 //lyxerr << "got so far: '" << cell << "'" << endl;
1496 error("Unmatched right delimiter");
1500 else if (t.cs() == "begin") {
1501 docstring const name = getArg('{', '}');
1502 environments_.push_back(name);
1504 if (name == "array" || name == "subarray") {
1505 docstring const valign = parse_verbatim_option() + 'c';
1506 docstring const halign = parse_verbatim_item();
1507 cell->push_back(MathAtom(new InsetMathArray(buf, name,
1508 InsetMathGrid::guessColumns(halign), 1, (char)valign[0], halign)));
1509 parse2(cell->back(), FLAG_END, mode, false);
1512 else if (name == "tabular") {
1513 docstring const valign = parse_verbatim_option() + 'c';
1514 docstring const halign = parse_verbatim_item();
1515 cell->push_back(MathAtom(new InsetMathTabular(buf, name,
1516 InsetMathGrid::guessColumns(halign), 1, (char)valign[0], halign)));
1517 parse2(cell->back(), FLAG_END, InsetMath::TEXT_MODE, false);
1520 else if (name == "split" || name == "cases") {
1521 cell->push_back(createInsetMath(name, buf));
1522 parse2(cell->back(), FLAG_END, mode, false);
1525 else if (name == "alignedat") {
1526 docstring const valign = parse_verbatim_option() + 'c';
1527 // ignore this for a while
1529 cell->push_back(MathAtom(new InsetMathSplit(buf, name, (char)valign[0])));
1530 parse2(cell->back(), FLAG_END, mode, false);
1533 else if (name == "math") {
1534 cell->push_back(MathAtom(new InsetMathEnsureMath(buf)));
1535 parse(cell->back().nucleus()->cell(0), FLAG_END, InsetMath::MATH_MODE);
1538 else if (name == "equation" || name == "equation*"
1539 || name == "displaymath") {
1540 if (mode != InsetMath::UNDECIDED_MODE) {
1541 error("bad math environment");
1544 cell->push_back(MathAtom(new InsetMathHull(buf, hullEquation)));
1545 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, (name == "equation"));
1548 else if (name == "eqnarray" || name == "eqnarray*") {
1549 if (mode != InsetMath::UNDECIDED_MODE) {
1550 error("bad math environment");
1553 cell->push_back(MathAtom(new InsetMathHull(buf, hullEqnArray)));
1554 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, !stared(name));
1557 else if (name == "align" || name == "align*") {
1558 if (mode != InsetMath::UNDECIDED_MODE) {
1559 error("bad math environment");
1562 cell->push_back(MathAtom(new InsetMathHull(buf, hullAlign)));
1563 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, !stared(name));
1566 else if (name == "flalign" || name == "flalign*") {
1567 if (mode != InsetMath::UNDECIDED_MODE) {
1568 error("bad math environment");
1571 cell->push_back(MathAtom(new InsetMathHull(buf, hullFlAlign)));
1572 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, !stared(name));
1575 else if (name == "alignat" || name == "alignat*") {
1576 if (mode != InsetMath::UNDECIDED_MODE) {
1577 error("bad math environment");
1580 // ignore this for a while
1582 cell->push_back(MathAtom(new InsetMathHull(buf, hullAlignAt)));
1583 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, !stared(name));
1586 else if (name == "xalignat" || name == "xalignat*") {
1587 if (mode != InsetMath::UNDECIDED_MODE) {
1588 error("bad math environment");
1591 // ignore this for a while
1593 cell->push_back(MathAtom(new InsetMathHull(buf, hullXAlignAt)));
1594 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, !stared(name));
1597 else if (name == "xxalignat") {
1598 if (mode != InsetMath::UNDECIDED_MODE) {
1599 error("bad math environment");
1602 // ignore this for a while
1604 cell->push_back(MathAtom(new InsetMathHull(buf, hullXXAlignAt)));
1605 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, !stared(name));
1608 else if (name == "multline" || name == "multline*") {
1609 if (mode != InsetMath::UNDECIDED_MODE) {
1610 error("bad math environment");
1613 cell->push_back(MathAtom(new InsetMathHull(buf, hullMultline)));
1614 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, !stared(name));
1617 else if (name == "gather" || name == "gather*") {
1618 if (mode != InsetMath::UNDECIDED_MODE) {
1619 error("bad math environment");
1622 cell->push_back(MathAtom(new InsetMathHull(buf, hullGather)));
1623 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, !stared(name));
1626 else if (latexkeys const * l = in_word_set(name)) {
1627 if (l->inset == "matrix") {
1628 cell->push_back(createInsetMath(name, buf));
1629 parse2(cell->back(), FLAG_END, mode, false);
1630 } else if (l->inset == "split") {
1631 docstring const valign = parse_verbatim_option() + 'c';
1632 cell->push_back(MathAtom(
1633 new InsetMathSplit(buf, name, (char)valign[0])));
1634 parse2(cell->back(), FLAG_END, mode, false);
1637 if (!(mode_ & Parse::QUIET)) {
1639 lyxerr << "found math environment `"
1641 << "' in symbols file with unsupported inset `"
1642 << to_utf8(l->inset)
1645 // create generic environment inset
1646 cell->push_back(MathAtom(new InsetMathEnv(buf, name)));
1647 parse(cell->back().nucleus()->cell(0), FLAG_END, mode);
1653 if (!(mode_ & Parse::QUIET)) {
1655 lyxerr << "found unknown math environment '"
1656 << to_utf8(name) << "'" << endl;
1658 // create generic environment inset
1659 cell->push_back(MathAtom(new InsetMathEnv(buf, name)));
1660 parse(cell->back().nucleus()->cell(0), FLAG_END, mode);
1664 else if (t.cs() == "kern") {
1669 Token const & t = getToken();
1673 while (num_tokens--)
1678 if (isValidLength(to_utf8(s)))
1682 cell->push_back(MathAtom(new InsetMathKern));
1684 cell->push_back(MathAtom(new InsetMathKern(s)));
1687 else if (t.cs() == "label") {
1688 // FIXME: This is swallowed in inline formulas
1689 docstring label = parse_verbatim_item();
1692 if (grid.asHullInset()) {
1693 grid.asHullInset()->label(cellrow, label);
1695 cell->push_back(createInsetMath(t.cs(), buf));
1696 cell->push_back(MathAtom(new InsetMathBrace(ar)));
1700 else if (t.cs() == "choose" || t.cs() == "over"
1701 || t.cs() == "atop" || t.cs() == "brace"
1702 || t.cs() == "brack") {
1703 MathAtom at = createInsetMath(t.cs(), buf);
1704 at.nucleus()->cell(0) = *cell;
1706 parse(at.nucleus()->cell(1), flags, mode);
1707 cell->push_back(at);
1711 else if (t.cs() == "color") {
1712 docstring const color = parse_verbatim_item();
1713 cell->push_back(MathAtom(new InsetMathColor(buf, true, color)));
1714 parse(cell->back().nucleus()->cell(0), flags, mode);
1718 else if (t.cs() == "textcolor") {
1719 docstring const color = parse_verbatim_item();
1720 cell->push_back(MathAtom(new InsetMathColor(buf, false, color)));
1721 parse(cell->back().nucleus()->cell(0), FLAG_ITEM, InsetMath::TEXT_MODE);
1724 else if (t.cs() == "normalcolor") {
1725 cell->push_back(createInsetMath(t.cs(), buf));
1726 parse(cell->back().nucleus()->cell(0), flags, mode);
1730 else if (t.cs() == "substack") {
1731 cell->push_back(createInsetMath(t.cs(), buf));
1732 parse2(cell->back(), FLAG_ITEM, mode, false);
1733 // Delete empty last row if present
1734 InsetMathGrid & subgrid =
1735 *(cell->back().nucleus()->asGridInset());
1736 if (subgrid.nrows() > 1)
1737 delEmptyLastRow(subgrid);
1740 else if (t.cs() == "xymatrix") {
1741 odocstringstream os;
1742 while (good() && nextToken().cat() != catBegin)
1743 os << getToken().asInput();
1744 cell->push_back(createInsetMath(t.cs() + os.str(), buf));
1745 parse2(cell->back(), FLAG_ITEM, mode, false);
1746 // Delete empty last row if present
1747 InsetMathGrid & subgrid =
1748 *(cell->back().nucleus()->asGridInset());
1749 if (subgrid.nrows() > 1)
1750 delEmptyLastRow(subgrid);
1753 else if (t.cs() == "Diagram") {
1754 odocstringstream os;
1755 while (good() && nextToken().cat() != catBegin)
1756 os << getToken().asInput();
1757 cell->push_back(createInsetMath(t.cs() + os.str(), buf));
1758 parse2(cell->back(), FLAG_ITEM, mode, false);
1761 else if (t.cs() == "framebox" || t.cs() == "makebox") {
1762 cell->push_back(createInsetMath(t.cs(), buf));
1763 parse(cell->back().nucleus()->cell(0), FLAG_OPTION, InsetMath::TEXT_MODE);
1764 parse(cell->back().nucleus()->cell(1), FLAG_OPTION, InsetMath::TEXT_MODE);
1765 parse(cell->back().nucleus()->cell(2), FLAG_ITEM, InsetMath::TEXT_MODE);
1768 else if (t.cs() == "tag") {
1769 if (nextToken().character() == '*') {
1771 cell->push_back(createInsetMath(t.cs() + '*', buf));
1773 cell->push_back(createInsetMath(t.cs(), buf));
1774 parse(cell->back().nucleus()->cell(0), FLAG_ITEM, InsetMath::TEXT_MODE);
1777 else if (t.cs() == "hspace") {
1778 bool const prot = nextToken().character() == '*';
1781 docstring const name = t.cs();
1782 docstring const arg = parse_verbatim_item();
1784 if (prot && arg == "\\fill")
1785 cell->push_back(MathAtom(new InsetMathSpace("hspace*{\\fill}", "")));
1786 else if (isValidLength(to_utf8(arg), &length))
1787 cell->push_back(MathAtom(new InsetMathSpace(length, prot)));
1789 // Since the Length class cannot use length variables
1790 // we must not create an InsetMathSpace.
1791 cell->push_back(MathAtom(new MathMacro(buf, name)));
1793 mathed_parse_cell(ar, '{' + arg + '}', mode_);
1799 else if (t.cs() == "infer") {
1801 parse(ar, FLAG_OPTION, mode);
1802 cell->push_back(createInsetMath(t.cs(), buf));
1803 parse2(cell->back(), FLAG_ITEM, mode, false);
1807 else if (1 && t.cs() == "ar") {
1808 auto_ptr<InsetMathXYArrow> p(new InsetMathXYArrow);
1809 // try to read target
1810 parse(p->cell(0), FLAG_OTPTION, mode);
1811 // try to read label
1812 if (nextToken().cat() == catSuper || nextToken().cat() == catSub) {
1813 p->up_ = nextToken().cat() == catSuper;
1815 parse(p->cell(1), FLAG_ITEM, mode);
1816 //lyxerr << "read label: " << p->cell(1) << endl;
1819 cell->push_back(MathAtom(p.release()));
1820 //lyxerr << "read cell: " << cell << endl;
1824 else if (t.cs() == "lyxmathsym") {
1826 if (getToken().cat() != catBegin) {
1827 error("'{' expected in \\" + t.cs());
1832 CatCode cat = nextToken().cat();
1833 while (good() && (count || cat != catEnd)) {
1834 if (cat == catBegin)
1836 else if (cat == catEnd)
1838 cmd += getToken().asInput();
1839 cat = nextToken().cat();
1841 if (getToken().cat() != catEnd) {
1842 error("'}' expected in \\" + t.cs());
1848 cmd = Encodings::fromLaTeXCommand(cmd,
1849 Encodings::MATH_CMD | Encodings::TEXT_CMD,
1851 for (size_t i = 0; i < cmd.size(); ++i)
1852 cell->push_back(MathAtom(new InsetMathChar(cmd[i])));
1854 char_type c = rem[0];
1855 cell->push_back(MathAtom(new InsetMathChar(c)));
1856 cmd = rem.substr(1);
1860 } while (!cmd.empty());
1863 else if (!t.cs().empty()) {
1864 bool const no_mhchem =
1865 (t.cs() == "ce" || t.cs() == "cf")
1866 && buf && buf->params().use_package("mhchem") ==
1867 BufferParams::package_off;
1869 bool const is_user_macro = no_mhchem ||
1870 (buf && (mode_ & Parse::TRACKMACRO
1871 ? buf->usermacros.count(t.cs()) != 0
1872 : buf->getMacro(t.cs(), false) != 0));
1874 latexkeys const * l = in_word_set(t.cs());
1875 if (l && !is_user_macro) {
1876 if (l->inset == "big") {
1878 docstring const delim = getToken().asInput();
1879 if (InsetMathBig::isBigInsetDelim(delim))
1880 cell->push_back(MathAtom(
1881 new InsetMathBig(t.cs(), delim)));
1883 cell->push_back(createInsetMath(t.cs(), buf));
1888 else if (l->inset == "font") {
1889 cell->push_back(createInsetMath(t.cs(), buf));
1890 parse(cell->back().nucleus()->cell(0),
1891 FLAG_ITEM, asMode(mode, l->extra));
1894 else if (l->inset == "oldfont") {
1895 cell->push_back(createInsetMath(t.cs(), buf));
1896 parse(cell->back().nucleus()->cell(0),
1897 flags | FLAG_ALIGN, asMode(mode, l->extra));
1898 if (prevToken().cat() != catAlign &&
1899 prevToken().cs() != "\\")
1904 else if (l->inset == "style") {
1905 cell->push_back(createInsetMath(t.cs(), buf));
1906 parse(cell->back().nucleus()->cell(0),
1907 flags | FLAG_ALIGN, mode);
1908 if (prevToken().cat() != catAlign &&
1909 prevToken().cs() != "\\")
1915 MathAtom at = createInsetMath(t.cs(), buf);
1916 for (InsetMath::idx_type i = 0; i < at->nargs(); ++i)
1917 parse(at.nucleus()->cell(i),
1918 FLAG_ITEM, asMode(mode, l->extra));
1919 cell->push_back(at);
1924 bool is_unicode_symbol = false;
1925 if (mode == InsetMath::TEXT_MODE && !is_user_macro) {
1927 docstring cmd = prevToken().asInput();
1928 CatCode cat = nextToken().cat();
1929 if (cat == catBegin) {
1931 while (good() && (count || cat != catEnd)) {
1932 cat = nextToken().cat();
1933 cmd += getToken().asInput();
1935 if (cat == catBegin)
1937 else if (cat == catEnd)
1943 char_type c = Encodings::fromLaTeXCommand(cmd,
1944 Encodings::MATH_CMD | Encodings::TEXT_CMD,
1945 is_combining, termination);
1947 if (cat == catLetter)
1949 cmd += getToken().asInput();
1951 if (cat == catLetter)
1953 c = Encodings::fromLaTeXCommand(cmd,
1954 Encodings::MATH_CMD | Encodings::TEXT_CMD,
1955 is_combining, termination);
1959 if (nextToken().cat() == catBegin) {
1961 if (nextToken().cat() == catEnd) {
1967 while (nextToken().cat() == catSpace) {
1973 is_unicode_symbol = true;
1974 cell->push_back(MathAtom(new InsetMathChar(c)));
1976 while (num_tokens--)
1980 if (!is_unicode_symbol) {
1981 MathAtom at = is_user_macro ?
1982 MathAtom(new MathMacro(buf, t.cs()))
1983 : createInsetMath(t.cs(), buf);
1984 InsetMath::mode_type m = mode;
1985 //if (m == InsetMath::UNDECIDED_MODE)
1986 //lyxerr << "default creation: m1: " << m << endl;
1987 if (at->currentMode() != InsetMath::UNDECIDED_MODE)
1988 m = at->currentMode();
1989 //lyxerr << "default creation: m2: " << m << endl;
1990 InsetMath::idx_type start = 0;
1991 // this fails on \bigg[...\bigg]
1993 //parse(opt, FLAG_OPTION, InsetMath::VERBATIM_MODE);
1994 //if (!opt.empty()) {
1996 // at.nucleus()->cell(0) = opt;
1998 for (InsetMath::idx_type i = start; i < at->nargs(); ++i) {
1999 parse(at.nucleus()->cell(i), FLAG_ITEM, m);
2002 cell->push_back(at);
2008 if (flags & FLAG_LEAVE) {
2009 flags &= ~FLAG_LEAVE;
2018 } // anonymous namespace
2021 bool mathed_parse_cell(MathData & ar, docstring const & str, Parse::flags f)
2023 return Parser(str, f, ar.buffer()).parse(ar, 0, f & Parse::TEXTMODE ?
2024 InsetMath::TEXT_MODE : InsetMath::MATH_MODE);
2028 bool mathed_parse_cell(MathData & ar, istream & is, Parse::flags f)
2030 return Parser(is, f, ar.buffer()).parse(ar, 0, f & Parse::TEXTMODE ?
2031 InsetMath::TEXT_MODE : InsetMath::MATH_MODE);
2035 bool mathed_parse_normal(Buffer * buf, MathAtom & t, docstring const & str,
2038 return Parser(str, f, buf).parse(t);
2042 bool mathed_parse_normal(Buffer * buf, MathAtom & t, Lexer & lex,
2045 return Parser(lex, f, buf).parse(t);
2049 bool mathed_parse_normal(InsetMathGrid & grid, docstring const & str,
2052 return Parser(str, f, &grid.buffer()).parse1(grid, 0, f & Parse::TEXTMODE ?
2053 InsetMath::TEXT_MODE : InsetMath::MATH_MODE, false);
2059 fill(theCatcode, theCatcode + 128, catOther);
2060 fill(theCatcode + 'a', theCatcode + 'z' + 1, catLetter);
2061 fill(theCatcode + 'A', theCatcode + 'Z' + 1, catLetter);
2063 theCatcode[int('\\')] = catEscape;
2064 theCatcode[int('{')] = catBegin;
2065 theCatcode[int('}')] = catEnd;
2066 theCatcode[int('$')] = catMath;
2067 theCatcode[int('&')] = catAlign;
2068 theCatcode[int('\n')] = catNewline;
2069 theCatcode[int('#')] = catParameter;
2070 theCatcode[int('^')] = catSuper;
2071 theCatcode[int('_')] = catSub;
2072 theCatcode[int(0x7f)] = catIgnore;
2073 theCatcode[int(' ')] = catSpace;
2074 theCatcode[int('\t')] = catSpace;
2075 theCatcode[int('\r')] = catNewline;
2076 theCatcode[int('~')] = catActive;
2077 theCatcode[int('%')] = catComment;