3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
8 * Full author contact details are available in file CREDITS.
13 If someone desperately needs partial "structures" (such as a few
14 cells of an array inset or similar) (s)he could uses the
15 following hack as starting point to write some macros:
20 \def\makeamptab{\catcode`\&=4\relax}
21 \def\makeampletter{\catcode`\&=11\relax}
22 \def\b{\makeampletter\expandafter\makeamptab\bi}
40 #include "MathParser.h"
42 #include "InsetMathArray.h"
43 #include "InsetMathBig.h"
44 #include "InsetMathBrace.h"
45 #include "InsetMathCancelto.h"
46 #include "InsetMathChar.h"
47 #include "InsetMathColor.h"
48 #include "InsetMathComment.h"
49 #include "InsetMathDelim.h"
50 #include "InsetMathEnsureMath.h"
51 #include "InsetMathEnv.h"
52 #include "InsetMathFrac.h"
53 #include "InsetMathKern.h"
54 #include "MathMacro.h"
55 #include "InsetMathPar.h"
56 #include "InsetMathRef.h"
57 #include "InsetMathRoot.h"
58 #include "InsetMathScript.h"
59 #include "InsetMathSideset.h"
60 #include "InsetMathSpace.h"
61 #include "InsetMathSplit.h"
62 #include "InsetMathSqrt.h"
63 #include "InsetMathStackrel.h"
64 #include "InsetMathString.h"
65 #include "InsetMathTabular.h"
66 #include "MathMacroTemplate.h"
67 #include "MathExtern.h"
68 #include "MathFactory.h"
69 #include "MathMacroArgument.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 MathData parse(unsigned flags, mode_type mode);
406 int lineno() const { return lineno_; }
409 /// store current position
411 /// restore previous position
413 /// forget last saved position
418 void parse2(MathAtom & at, unsigned flags, mode_type mode, bool numbered);
419 /// get arg delimited by 'left' and 'right'
420 docstring getArg(char_type left, char_type right);
424 void error(string const & msg);
425 void error(docstring const & msg) { error(to_utf8(msg)); }
426 /// dump contents to screen
428 /// Only use this for reading from .lyx file format (see
429 /// implementation for reason)
430 void tokenize(istream & is);
432 void tokenize(docstring const & s);
434 void skipSpaceTokens(idocstream & is, char_type c);
436 void push_back(Token const & t);
440 Token const & prevToken() const;
442 Token const & nextToken() const;
444 Token const & getToken();
445 /// skips spaces if any
448 void lex(docstring const & s);
452 docstring parse_verbatim_item();
454 docstring parse_verbatim_option();
459 vector<Token> tokens_;
463 std::vector<unsigned> positions_;
464 /// Stack of active environments
465 vector<docstring> environments_;
475 Parser::Parser(Lexer & lexer, parse_mode mode, Buffer * buf)
476 : lineno_(lexer.lineNumber()), pos_(0), mode_(mode), success_(true),
479 tokenize(lexer.getStream());
484 Parser::Parser(istream & is, parse_mode mode, Buffer * buf)
485 : lineno_(0), pos_(0), mode_(mode), success_(true), buffer_(buf)
491 Parser::Parser(docstring const & str, parse_mode mode, Buffer * buf)
492 : lineno_(0), pos_(0), mode_(mode), success_(true), buffer_(buf)
498 void Parser::push_back(Token const & t)
500 tokens_.push_back(t);
504 void Parser::pop_back()
510 Token const & Parser::prevToken() const
512 static const Token dummy;
513 return pos_ > 0 ? tokens_[pos_ - 1] : dummy;
517 Token const & Parser::nextToken() const
519 static const Token dummy;
520 return good() ? tokens_[pos_] : dummy;
524 Token const & Parser::getToken()
526 static const Token dummy;
527 //lyxerr << "looking at token " << tokens_[pos_] << " pos: " << pos_ << endl;
528 return good() ? tokens_[pos_++] : dummy;
532 void Parser::skipSpaces()
534 while (nextToken().cat() == catSpace || nextToken().cat() == catNewline)
539 void Parser::putback()
545 void Parser::pushPosition()
547 positions_.push_back(pos_);
551 void Parser::popPosition()
553 pos_ = positions_.back();
554 positions_.pop_back();
558 void Parser::dropPosition()
560 positions_.pop_back();
564 bool Parser::good() const
566 return pos_ < tokens_.size();
570 char_type Parser::getChar()
573 error("The input stream is not well...");
576 return tokens_[pos_++].character();
580 docstring Parser::getArg(char_type left, char_type right)
588 char_type c = getChar();
593 while ((c = getChar()) != right && good())
600 void Parser::skipSpaceTokens(idocstream & is, char_type c)
602 // skip trailing spaces
603 while (catcode(c) == catSpace || catcode(c) == catNewline)
606 //lyxerr << "putting back: " << c << endl;
611 void Parser::tokenize(istream & is)
613 // eat everything up to the next \end_inset or end of stream
614 // and store it in s for further tokenization
619 if (s.size() >= 10 && s.substr(s.size() - 10) == "\\end_inset") {
620 s = s.substr(0, s.size() - 10);
624 // Remove the space after \end_inset
625 if (is.get(c) && c != ' ')
629 tokenize(from_utf8(s));
633 void Parser::tokenize(docstring const & buffer)
635 idocstringstream is(mode_ & Parse::VERBATIM
636 ? escapeSpecialChars(buffer, mode_ & Parse::TEXTMODE)
637 : buffer, ios::in | ios::binary);
641 //lyxerr << "reading c: " << c << endl;
643 switch (catcode(c)) {
647 if (catcode(c) == catNewline)
648 ; //push_back(Token("par"));
650 push_back(Token('\n', catNewline));
658 while (is.get(c) && catcode(c) != catNewline)
668 error("unexpected end of input");
673 if (catcode(c) == catLetter) {
675 while (is.get(c) && catcode(c) == catLetter)
677 skipSpaceTokens(is, c);
686 push_back(Token(c, catcode(c)));
688 skipSpaceTokens(is, c);
693 if (!(mode_ & Parse::QUIET))
694 lyxerr << "ignoring a char: " << int(c) << endl;
699 push_back(Token(c, catcode(c)));
709 void Parser::dump() const
711 lyxerr << "\nTokens: ";
712 for (unsigned i = 0; i < tokens_.size(); ++i) {
715 lyxerr << tokens_[i];
717 lyxerr << " pos: " << pos_ << endl;
721 void Parser::error(string const & msg)
724 if (!(mode_ & Parse::QUIET)) {
725 lyxerr << "Line ~" << lineno_ << ": Math parse error: "
732 bool Parser::parse(MathAtom & at)
735 MathData ar(buffer_);
736 parse(ar, false, InsetMath::UNDECIDED_MODE);
737 if (ar.size() != 1 || ar.front()->getType() == hullNone) {
738 if (!(mode_ & Parse::QUIET))
739 lyxerr << "unusual contents found: " << ar << endl;
740 at = MathAtom(new InsetMathPar(buffer_, ar));
741 //if (at->nargs() > 0)
742 // at.nucleus()->cell(0) = ar;
744 // lyxerr << "unusual contents found: " << ar << endl;
752 docstring Parser::parse_verbatim_option()
756 if (nextToken().character() == '[') {
757 Token t = getToken();
758 for (Token t = getToken(); t.character() != ']' && good(); t = getToken()) {
759 if (t.cat() == catBegin) {
761 res += '{' + parse_verbatim_item() + '}';
770 docstring Parser::parse_verbatim_item()
774 if (nextToken().cat() == catBegin) {
775 Token t = getToken();
776 for (Token t = getToken(); t.cat() != catEnd && good(); t = getToken()) {
777 if (t.cat() == catBegin) {
779 res += '{' + parse_verbatim_item() + '}';
789 MathData Parser::parse(unsigned flags, mode_type mode)
791 MathData ar(buffer_);
792 parse(ar, flags, mode);
797 bool Parser::parse(MathData & array, unsigned flags, mode_type mode)
799 InsetMathGrid grid(buffer_, 1, 1);
800 parse1(grid, flags, mode, false);
801 array = grid.cell(0);
806 void Parser::parse2(MathAtom & at, const unsigned flags, const mode_type mode,
809 parse1(*(at.nucleus()->asGridInset()), flags, mode, numbered);
813 bool Parser::parse1(InsetMathGrid & grid, unsigned flags,
814 const mode_type mode, const bool numbered)
817 InsetMathGrid::row_type cellrow = 0;
818 InsetMathGrid::col_type cellcol = 0;
819 MathData * cell = &grid.cell(grid.index(cellrow, cellcol));
820 Buffer * buf = buffer_;
822 if (grid.asHullInset())
823 grid.asHullInset()->numbered(cellrow, numbered);
826 //lyxerr << " flags: " << flags << endl;
827 //lyxerr << " mode: " << mode << endl;
828 //lyxerr << "grid: " << grid << endl;
831 Token const & t = getToken();
834 lyxerr << "t: " << t << " flags: " << flags << endl;
835 lyxerr << "mode: " << mode << endl;
840 if (flags & FLAG_ITEM) {
842 if (t.cat() == catBegin) {
843 // skip the brace and collect everything to the next matching
845 parse1(grid, FLAG_BRACE_LAST, mode, numbered);
849 // handle only this single token, leave the loop if done
854 if (flags & FLAG_BRACED) {
855 if (t.cat() == catSpace)
858 if (t.cat() != catBegin) {
859 error("opening brace expected");
863 // skip the brace and collect everything to the next matching
865 flags = FLAG_BRACE_LAST;
869 if (flags & FLAG_OPTION) {
870 if (t.cat() == catOther && t.character() == '[') {
872 parse(ar, FLAG_BRACK_LAST, mode);
875 // no option found, put back token and we are done
884 if (t.cat() == catMath) {
885 if (mode != InsetMath::MATH_MODE) {
886 // we are inside some text mode thingy, so opening new math is allowed
887 Token const & n = getToken();
888 if (n.cat() == catMath) {
889 // TeX's $$...$$ syntax for displayed math
890 if (mode == InsetMath::UNDECIDED_MODE) {
891 cell->push_back(MathAtom(new InsetMathHull(buf, hullEquation)));
892 parse2(cell->back(), FLAG_SIMPLE, InsetMath::MATH_MODE, false);
893 getToken(); // skip the second '$' token
895 // This is not an outer hull and display math is
896 // not allowed inside text mode environments.
897 error("bad math environment $$");
901 // simple $...$ stuff
903 if (mode == InsetMath::UNDECIDED_MODE) {
904 cell->push_back(MathAtom(new InsetMathHull(buf, hullSimple)));
905 parse2(cell->back(), FLAG_SIMPLE, InsetMath::MATH_MODE, false);
907 // Don't create nested math hulls (bug #5392)
908 cell->push_back(MathAtom(new InsetMathEnsureMath(buf)));
909 parse(cell->back().nucleus()->cell(0), FLAG_SIMPLE, InsetMath::MATH_MODE);
914 else if (flags & FLAG_SIMPLE) {
915 // this is the end of the formula
920 Token const & n = getToken();
921 if (n.cat() == catMath) {
922 error("something strange in the parser");
925 // This is inline math ($...$), but the parser thinks we are
926 // already in math mode and latex would issue an error, unless we
927 // are inside a text mode user macro. We have no way to tell, so
928 // let's play safe by using \ensuremath, as it will work in any case.
930 cell->push_back(MathAtom(new InsetMathEnsureMath(buf)));
931 parse(cell->back().nucleus()->cell(0), FLAG_SIMPLE, InsetMath::MATH_MODE);
936 else if (t.cat() == catLetter)
937 cell->push_back(MathAtom(new InsetMathChar(t.character())));
939 else if (t.cat() == catSpace && mode != InsetMath::MATH_MODE) {
940 if (cell->empty() || cell->back()->getChar() != ' ')
941 cell->push_back(MathAtom(new InsetMathChar(t.character())));
944 else if (t.cat() == catNewline && mode != InsetMath::MATH_MODE) {
945 if (cell->empty() || cell->back()->getChar() != ' ')
946 cell->push_back(MathAtom(new InsetMathChar(' ')));
949 else if (t.cat() == catParameter) {
950 Token const & n = getToken();
951 cell->push_back(MathAtom(new MathMacroArgument(n.character()-'0')));
954 else if (t.cat() == catActive)
955 cell->push_back(MathAtom(new InsetMathSpace(string(1, t.character()), "")));
957 else if (t.cat() == catBegin) {
959 parse(ar, FLAG_BRACE_LAST, mode);
960 // do not create a BraceInset if they were written by LyX
961 // this helps to keep the annoyance of "a choose b" to a minimum
962 if (ar.size() == 1 && ar[0]->extraBraces())
965 cell->push_back(MathAtom(new InsetMathBrace(ar)));
968 else if (t.cat() == catEnd) {
969 if (flags & FLAG_BRACE_LAST)
971 error("found '}' unexpectedly");
972 //LASSERT(false, /**/);
973 //add(cell, '}', LM_TC_TEX);
976 else if (t.cat() == catAlign) {
977 //lyxerr << " column now " << (cellcol + 1)
978 // << " max: " << grid.ncols() << endl;
979 if (flags & FLAG_ALIGN)
981 if (addCol(grid, cellcol))
982 cell = &grid.cell(grid.index(cellrow, cellcol));
985 else if (t.cat() == catSuper || t.cat() == catSub) {
986 bool up = (t.cat() == catSuper);
987 // we need no new script inset if the last thing was a scriptinset,
988 // which has that script already not the same script already
990 cell->push_back(MathAtom(new InsetMathScript(buf, up)));
991 else if (cell->back()->asScriptInset() &&
992 !cell->back()->asScriptInset()->has(up))
993 cell->back().nucleus()->asScriptInset()->ensure(up);
994 else if (cell->back()->asScriptInset())
995 cell->push_back(MathAtom(new InsetMathScript(buf, up)));
997 cell->back() = MathAtom(new InsetMathScript(buf, cell->back(), up));
998 InsetMathScript * p = cell->back().nucleus()->asScriptInset();
999 // special handling of {}-bases
1000 // Here we could remove the brace inset for things
1001 // like {a'}^2 and add the braces back in
1002 // InsetMathScript::write().
1003 // We do not do it, since it is not possible to detect
1004 // reliably whether the braces are needed because the
1005 // nucleus contains more than one symbol, or whether
1006 // they are needed for unknown commands like \xx{a}_0
1007 // or \yy{a}{b}_0. This was done in revision 14819
1008 // in an unreliable way. See this thread
1009 // http://www.mail-archive.com/lyx-devel%40lists.lyx.org/msg104917.html
1010 // for more details.
1011 // However, we remove empty braces because they look
1012 // ugly on screen and we are sure that they were added
1013 // by the write() method (and will be re-added on save).
1014 if (p->nuc().size() == 1 &&
1015 p->nuc().back()->asBraceInset() &&
1016 p->nuc().back()->asBraceInset()->cell(0).empty())
1019 parse(p->cell(p->idxOfScript(up)), FLAG_ITEM, mode);
1026 else if (t.character() == ']' && (flags & FLAG_BRACK_LAST)) {
1027 //lyxerr << "finished reading option" << endl;
1031 else if (t.cat() == catOther) {
1032 char_type c = t.character();
1033 if (isAsciiOrMathAlpha(c)
1034 || mode_ & Parse::VERBATIM
1035 || !(mode_ & Parse::USETEXT)
1036 || mode == InsetMath::TEXT_MODE) {
1037 cell->push_back(MathAtom(new InsetMathChar(c)));
1039 MathAtom at = createInsetMath("text", buf);
1040 at.nucleus()->cell(0).push_back(MathAtom(new InsetMathChar(c)));
1041 while (nextToken().cat() == catOther
1042 && !isAsciiOrMathAlpha(nextToken().character())) {
1043 c = getToken().character();
1044 at.nucleus()->cell(0).push_back(MathAtom(new InsetMathChar(c)));
1046 cell->push_back(at);
1050 else if (t.cat() == catComment) {
1053 Token const & t = getToken();
1054 if (t.cat() == catNewline)
1058 cell->push_back(MathAtom(new InsetMathComment(buf, s)));
1063 // control sequences
1066 else if (t.cs() == "lyxlock") {
1068 cell->back().nucleus()->lock(true);
1071 else if ((t.cs() == "global" && nextToken().cs() == "def") ||
1073 if (t.cs() == "global")
1077 docstring name = getToken().cs();
1082 while (good() && nextToken().cat() != catBegin) {
1083 pars += getToken().cs();
1090 parse(def, FLAG_ITEM, InsetMath::UNDECIDED_MODE);
1092 // is a version for display attached?
1095 if (nextToken().cat() == catBegin)
1096 parse(display, FLAG_ITEM, InsetMath::MATH_MODE);
1098 cell->push_back(MathAtom(new MathMacroTemplate(buf,
1099 name, nargs, 0, MacroTypeDef,
1100 vector<MathData>(), def, display)));
1102 if (buf && (mode_ & Parse::TRACKMACRO))
1103 buf->usermacros.insert(name);
1106 else if (t.cs() == "newcommand" ||
1107 t.cs() == "renewcommand" ||
1108 t.cs() == "newlyxcommand") {
1110 if (getToken().cat() != catBegin) {
1111 error("'{' in \\newcommand expected (1) ");
1114 docstring name = getToken().cs();
1115 if (getToken().cat() != catEnd) {
1116 error("'}' in \\newcommand expected");
1121 docstring const arg = getArg('[', ']');
1124 nargs = convert<int>(arg);
1126 // optional argument given?
1129 vector<MathData> optionalValues;
1130 while (nextToken().character() == '[') {
1132 optionalValues.push_back(MathData());
1133 parse(optionalValues[optionals], FLAG_BRACK_LAST, mode);
1138 parse(def, FLAG_ITEM, InsetMath::UNDECIDED_MODE);
1140 // is a version for display attached?
1143 if (nextToken().cat() == catBegin)
1144 parse(display, FLAG_ITEM, InsetMath::MATH_MODE);
1146 cell->push_back(MathAtom(new MathMacroTemplate(buf,
1147 name, nargs, optionals, MacroTypeNewcommand,
1148 optionalValues, def, display)));
1150 if (buf && (mode_ & Parse::TRACKMACRO))
1151 buf->usermacros.insert(name);
1154 else if (t.cs() == "newcommandx" ||
1155 t.cs() == "renewcommandx") {
1156 // \newcommandx{\foo}[2][usedefault, addprefix=\global,1=default]{#1,#2}
1159 if (nextToken().cat() == catBegin) {
1161 name = getToken().cs();
1162 if (getToken().cat() != catEnd) {
1163 error("'}' in \\newcommandx expected");
1167 name = getToken().cs();
1170 docstring const arg = getArg('[', ']');
1172 error("[num] in \\newcommandx expected");
1175 int nargs = convert<int>(arg);
1179 vector<MathData> optionalValues;
1180 if (nextToken().character() == '[') {
1184 // handle 'opt=value' options, separated by ','.
1186 while (nextToken().character() != ']' && good()) {
1187 if (nextToken().character() >= '1'
1188 && nextToken().character() <= '9') {
1189 // optional value -> get parameter number
1190 int n = getChar() - '0';
1192 error("Arity of \\newcommandx too low "
1193 "for given optional parameter.");
1198 if (getToken().character() != '=') {
1199 error("'=' and optional parameter value "
1200 "expected for \\newcommandx");
1205 int optNum = max(size_t(n), optionalValues.size());
1206 optionalValues.resize(optNum);
1207 optionalValues[n - 1].clear();
1208 while (nextToken().character() != ']'
1209 && nextToken().character() != ',') {
1211 parse(data, FLAG_ITEM, InsetMath::UNDECIDED_MODE);
1212 optionalValues[n - 1].append(data);
1214 optionals = max(n, optionals);
1215 } else if (nextToken().cat() == catLetter) {
1216 // we in fact ignore every non-optional
1221 while (nextToken().cat() == catLetter)
1227 if (nextToken().character() == '=') {
1229 while (nextToken().character() != ']'
1230 && nextToken().character() != ',')
1231 parse(value, FLAG_ITEM,
1232 InsetMath::UNDECIDED_MODE);
1235 error("option for \\newcommandx expected");
1241 if (nextToken().character() == ',') {
1244 } else if (nextToken().character() != ']') {
1245 error("Expecting ',' or ']' in options "
1246 "of \\newcommandx");
1259 parse(def, FLAG_ITEM, InsetMath::UNDECIDED_MODE);
1261 // is a version for display attached?
1264 if (nextToken().cat() == catBegin)
1265 parse(display, FLAG_ITEM, InsetMath::MATH_MODE);
1267 cell->push_back(MathAtom(new MathMacroTemplate(buf,
1268 name, nargs, optionals, MacroTypeNewcommandx,
1269 optionalValues, def, display)));
1271 if (buf && (mode_ & Parse::TRACKMACRO))
1272 buf->usermacros.insert(name);
1275 else if (t.cs() == "(") {
1276 if (mode == InsetMath::UNDECIDED_MODE) {
1277 cell->push_back(MathAtom(new InsetMathHull(buf, hullSimple)));
1278 parse2(cell->back(), FLAG_SIMPLE2, InsetMath::MATH_MODE, false);
1280 // Don't create nested math hulls (bug #5392)
1281 cell->push_back(MathAtom(new InsetMathEnsureMath(buf)));
1282 parse(cell->back().nucleus()->cell(0), FLAG_SIMPLE2, InsetMath::MATH_MODE);
1286 else if (t.cs() == "[") {
1287 if (mode != InsetMath::UNDECIDED_MODE) {
1288 error("bad math environment [");
1291 cell->push_back(MathAtom(new InsetMathHull(buf, hullEquation)));
1292 parse2(cell->back(), FLAG_EQUATION, InsetMath::MATH_MODE, false);
1295 else if (t.cs() == "protect")
1296 // ignore \\protect, will hopefully be re-added during output
1299 else if (t.cs() == "end") {
1300 if (flags & FLAG_END) {
1301 // eat environment name
1302 docstring const name = getArg('{', '}');
1303 if (environments_.empty())
1304 error("'found \\end{" + name +
1305 "}' without matching '\\begin{" +
1307 else if (name != environments_.back())
1308 error("'\\end{" + name +
1309 "}' does not match '\\begin{" +
1310 environments_.back() + "}'");
1312 environments_.pop_back();
1313 // Delete empty last row in matrix
1315 // If you abuse InsetMathGrid for
1316 // non-matrix like structures you
1317 // probably need to refine this test.
1318 // Right now we only have to test for
1319 // single line hull insets.
1320 if (grid.nrows() > 1 && innerHull(name))
1321 delEmptyLastRow(grid);
1325 error("found 'end' unexpectedly");
1328 else if (t.cs() == ")") {
1329 if (flags & FLAG_SIMPLE2)
1331 error("found '\\)' unexpectedly");
1334 else if (t.cs() == "]") {
1335 if (flags & FLAG_EQUATION)
1337 error("found '\\]' unexpectedly");
1340 else if (t.cs() == "\\") {
1341 if (flags & FLAG_ALIGN)
1343 bool starred = false;
1345 if (nextToken().asInput() == "*") {
1348 } else if (nextToken().asInput() == "[")
1349 arg = getArg('[', ']');
1351 error("missing token after \\\\");
1352 // skip "{}" added in front of "[" (the
1353 // counterpart is in InsetMathGrid::eolString())
1354 // skip spaces because formula could come from tex2lyx
1355 bool skipBraces = false;
1357 if (nextToken().cat() == catBegin) {
1359 if (nextToken().cat() == catEnd) {
1363 if (nextToken().asInput() == "[")
1372 bool const added = addRow(grid, cellrow, arg, !starred);
1375 if (grid.asHullInset())
1376 grid.asHullInset()->numbered(
1378 cell = &grid.cell(grid.index(cellrow,
1383 else if (t.cs() == "multicolumn") {
1384 // extract column count and insert dummy cells
1386 parse(count, FLAG_ITEM, mode);
1388 if (!extractNumber(count, cols)) {
1390 error("can't extract number of multicolumn cells");
1392 // resize the table if necessary
1393 size_t first = grid.index(cellrow, cellcol);
1394 for (int i = 1; i < cols; ++i) {
1395 if (addCol(grid, cellcol)) {
1396 size_t const idx = grid.index(cellrow, cellcol);
1397 grid.cellinfo(idx).multi_ =
1398 InsetMathGrid::CELL_PART_OF_MULTICOLUMN;
1402 // the first cell is the real thing, not a dummy
1403 cell = &grid.cell(first);
1404 grid.cellinfo(first).multi_ = InsetMathGrid::CELL_BEGIN_OF_MULTICOLUMN;
1406 // read special alignment
1408 parse(align, FLAG_ITEM, mode);
1409 grid.cellinfo(first).align_ = asString(align);
1411 // parse the remaining contents into the "real" cell
1412 parse(*cell, FLAG_ITEM, mode);
1415 else if (t.cs() == "limits" || t.cs() == "nolimits") {
1416 CatCode const cat = nextToken().cat();
1417 if (cat == catSuper || cat == catSub)
1418 limits = t.cs() == "limits" ? 1 : -1;
1420 MathAtom at = createInsetMath(t.cs(), buf);
1421 cell->push_back(at);
1425 // \notag is the same as \nonumber if amsmath is used
1426 else if ((t.cs() == "nonumber" || t.cs() == "notag") &&
1428 grid.asHullInset()->numbered(cellrow, false);
1430 else if (t.cs() == "number" && grid.asHullInset())
1431 grid.asHullInset()->numbered(cellrow, true);
1433 else if (t.cs() == "hline") {
1434 grid.rowinfo(cellrow).lines_ ++;
1437 else if (t.cs() == "sqrt") {
1439 parse(ar, FLAG_OPTION, mode);
1441 cell->push_back(MathAtom(new InsetMathRoot(buf)));
1442 cell->back().nucleus()->cell(0) = ar;
1443 parse(cell->back().nucleus()->cell(1), FLAG_ITEM, mode);
1445 cell->push_back(MathAtom(new InsetMathSqrt(buf)));
1446 parse(cell->back().nucleus()->cell(0), FLAG_ITEM, mode);
1450 else if (t.cs() == "cancelto") {
1452 parse(ar, FLAG_ITEM, mode);
1453 cell->push_back(MathAtom(new InsetMathCancelto(buf)));
1454 cell->back().nucleus()->cell(1) = ar;
1455 parse(cell->back().nucleus()->cell(0), FLAG_ITEM, mode);
1458 else if (t.cs() == "unit") {
1459 // Allowed formats \unit[val]{unit}
1461 parse(ar, FLAG_OPTION, mode);
1463 cell->push_back(MathAtom(new InsetMathFrac(buf, InsetMathFrac::UNIT)));
1464 cell->back().nucleus()->cell(0) = ar;
1465 parse(cell->back().nucleus()->cell(1), FLAG_ITEM, mode);
1467 cell->push_back(MathAtom(new InsetMathFrac(buf, InsetMathFrac::UNIT, 1)));
1468 parse(cell->back().nucleus()->cell(0), FLAG_ITEM, mode);
1472 else if (t.cs() == "unitfrac") {
1473 // Here allowed formats are \unitfrac[val]{num}{denom}
1475 parse(ar, FLAG_OPTION, mode);
1477 cell->push_back(MathAtom(new InsetMathFrac(buf, InsetMathFrac::UNITFRAC, 3)));
1478 cell->back().nucleus()->cell(2) = ar;
1480 cell->push_back(MathAtom(new InsetMathFrac(buf, InsetMathFrac::UNITFRAC)));
1482 parse(cell->back().nucleus()->cell(0), FLAG_ITEM, mode);
1483 parse(cell->back().nucleus()->cell(1), FLAG_ITEM, mode);
1486 else if (t.cs() == "cfrac") {
1487 // allowed formats are \cfrac[pos]{num}{denom}
1488 docstring const arg = getArg('[', ']');
1489 //lyxerr << "got so far: '" << arg << "'" << endl;
1491 cell->push_back(MathAtom(new InsetMathFrac(buf, InsetMathFrac::CFRACLEFT)));
1492 else if (arg == "r")
1493 cell->push_back(MathAtom(new InsetMathFrac(buf, InsetMathFrac::CFRACRIGHT)));
1494 else if (arg.empty() || arg == "c")
1495 cell->push_back(MathAtom(new InsetMathFrac(buf, InsetMathFrac::CFRAC)));
1497 error("found invalid optional argument");
1500 parse(cell->back().nucleus()->cell(0), FLAG_ITEM, mode);
1501 parse(cell->back().nucleus()->cell(1), FLAG_ITEM, mode);
1504 else if (t.cs() == "sideset") {
1505 // Here allowed formats are \sideset{_{bl}^{tl}}{_{br}^{tr}}{operator}
1507 InsetMathScript * script[2] = {0, 0};
1508 for (int i = 0; i < 2; ++i) {
1509 parse(ar[i], FLAG_ITEM, mode);
1510 if (ar[i].size() == 1)
1511 script[i] = ar[i][0].nucleus()->asScriptInset();
1513 bool const hasscript[2] = {script[0] ? true : false, script[1] ? true : false};
1514 cell->push_back(MathAtom(new InsetMathSideset(buf, hasscript[0], hasscript[1])));
1516 if (script[0]->hasDown())
1517 cell->back().nucleus()->cell(1) = script[0]->down();
1518 if (script[0]->hasUp())
1519 cell->back().nucleus()->cell(2) = script[0]->up();
1521 cell->back().nucleus()->cell(1) = ar[0];
1523 if (script[1]->hasDown())
1524 cell->back().nucleus()->cell(2 + hasscript[0]) = script[1]->down();
1525 if (script[1]->hasUp())
1526 cell->back().nucleus()->cell(3 + hasscript[0]) = script[1]->up();
1528 cell->back().nucleus()->cell(2 + hasscript[0]) = ar[1];
1529 parse(cell->back().nucleus()->cell(0), FLAG_ITEM, mode);
1532 else if (t.cs() == "stackrel") {
1533 // Here allowed formats are \stackrel[subscript]{superscript}{operator}
1535 parse(ar, FLAG_OPTION, mode);
1536 cell->push_back(MathAtom(new InsetMathStackrel(buf, !ar.empty())));
1538 cell->back().nucleus()->cell(2) = ar;
1539 parse(cell->back().nucleus()->cell(0), FLAG_ITEM, mode);
1540 parse(cell->back().nucleus()->cell(1), FLAG_ITEM, mode);
1543 else if (t.cs() == "xrightarrow" || t.cs() == "xleftarrow") {
1544 cell->push_back(createInsetMath(t.cs(), buf));
1545 parse(cell->back().nucleus()->cell(1), FLAG_OPTION, mode);
1546 parse(cell->back().nucleus()->cell(0), FLAG_ITEM, mode);
1549 else if (t.cs() == "xhookrightarrow" || t.cs() == "xhookleftarrow" ||
1550 t.cs() == "xRightarrow" || t.cs() == "xLeftarrow" ||
1551 t.cs() == "xleftrightarrow" || t.cs() == "xLeftrightarrow" ||
1552 t.cs() == "xrightharpoondown" || t.cs() == "xrightharpoonup" ||
1553 t.cs() == "xleftharpoondown" || t.cs() == "xleftharpoonup" ||
1554 t.cs() == "xleftrightharpoons" || t.cs() == "xrightleftharpoons" ||
1555 t.cs() == "xmapsto") {
1556 cell->push_back(createInsetMath(t.cs(), buf));
1557 parse(cell->back().nucleus()->cell(1), FLAG_OPTION, mode);
1558 parse(cell->back().nucleus()->cell(0), FLAG_ITEM, mode);
1561 else if (t.cs() == "ref" || t.cs() == "eqref" || t.cs() == "prettyref"
1562 || t.cs() == "pageref" || t.cs() == "vpageref" || t.cs() == "vref") {
1563 cell->push_back(MathAtom(new InsetMathRef(buf, t.cs())));
1564 docstring const opt = parse_verbatim_option();
1565 docstring const ref = parse_verbatim_item();
1567 cell->back().nucleus()->cell(1).push_back(
1568 MathAtom(new InsetMathString(opt)));
1570 cell->back().nucleus()->cell(0).push_back(
1571 MathAtom(new InsetMathString(ref)));
1574 else if (t.cs() == "left") {
1576 Token const & tl = getToken();
1577 // \| and \Vert are equivalent, and InsetMathDelim
1579 // FIXME: fix this in InsetMathDelim itself!
1580 docstring const l = tl.cs() == "|" ? from_ascii("Vert") : tl.asString();
1582 parse(ar, FLAG_RIGHT, mode);
1586 Token const & tr = getToken();
1587 docstring const r = tr.cs() == "|" ? from_ascii("Vert") : tr.asString();
1588 cell->push_back(MathAtom(new InsetMathDelim(buf, l, r, ar)));
1591 else if (t.cs() == "right") {
1592 if (flags & FLAG_RIGHT)
1594 //lyxerr << "got so far: '" << cell << "'" << endl;
1595 error("Unmatched right delimiter");
1599 else if (t.cs() == "begin") {
1600 docstring const name = getArg('{', '}');
1604 error("found invalid environment");
1608 environments_.push_back(name);
1610 if (name == "array" || name == "subarray") {
1611 docstring const valign = parse_verbatim_option() + 'c';
1612 docstring const halign = parse_verbatim_item();
1613 cell->push_back(MathAtom(new InsetMathArray(buf, name,
1614 InsetMathGrid::guessColumns(halign), 1, (char)valign[0], halign)));
1615 parse2(cell->back(), FLAG_END, mode, false);
1618 else if (name == "tabular") {
1619 docstring const valign = parse_verbatim_option() + 'c';
1620 docstring const halign = parse_verbatim_item();
1621 cell->push_back(MathAtom(new InsetMathTabular(buf, name,
1622 InsetMathGrid::guessColumns(halign), 1, (char)valign[0], halign)));
1623 parse2(cell->back(), FLAG_END, InsetMath::TEXT_MODE, false);
1626 else if (name == "split" || name == "cases") {
1627 cell->push_back(createInsetMath(name, buf));
1628 parse2(cell->back(), FLAG_END, mode, false);
1631 else if (name == "alignedat") {
1632 docstring const valign = parse_verbatim_option() + 'c';
1633 // ignore this for a while
1635 cell->push_back(MathAtom(new InsetMathSplit(buf, name, (char)valign[0])));
1636 parse2(cell->back(), FLAG_END, mode, false);
1639 else if (name == "math") {
1640 if (mode == InsetMath::UNDECIDED_MODE) {
1641 cell->push_back(MathAtom(new InsetMathHull(buf, hullSimple)));
1642 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, false);
1644 // Don't create nested math hulls (bug #5392)
1645 cell->push_back(MathAtom(new InsetMathEnsureMath(buf)));
1646 parse(cell->back().nucleus()->cell(0), FLAG_END, InsetMath::MATH_MODE);
1650 else if (name == "equation" || name == "equation*"
1651 || name == "displaymath") {
1652 if (mode != InsetMath::UNDECIDED_MODE) {
1653 error("bad math environment " + name);
1656 cell->push_back(MathAtom(new InsetMathHull(buf, hullEquation)));
1657 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, (name == "equation"));
1660 else if (name == "eqnarray" || name == "eqnarray*") {
1661 if (mode != InsetMath::UNDECIDED_MODE) {
1662 error("bad math environment " + name);
1665 cell->push_back(MathAtom(new InsetMathHull(buf, hullEqnArray)));
1666 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, !stared(name));
1669 else if (name == "align" || name == "align*") {
1670 if (mode == InsetMath::UNDECIDED_MODE) {
1671 cell->push_back(MathAtom(new InsetMathHull(buf, hullAlign)));
1672 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, !stared(name));
1674 cell->push_back(MathAtom(new InsetMathSplit(buf, name,
1675 'c', !stared(name))));
1676 parse2(cell->back(), FLAG_END, mode, !stared(name));
1680 else if (name == "flalign" || name == "flalign*") {
1681 if (mode != InsetMath::UNDECIDED_MODE) {
1682 error("bad math environment " + name);
1685 cell->push_back(MathAtom(new InsetMathHull(buf, hullFlAlign)));
1686 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, !stared(name));
1689 else if (name == "alignat" || name == "alignat*") {
1690 if (mode != InsetMath::UNDECIDED_MODE) {
1691 error("bad math environment " + name);
1694 // ignore this for a while
1696 cell->push_back(MathAtom(new InsetMathHull(buf, hullAlignAt)));
1697 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, !stared(name));
1700 else if (name == "xalignat" || name == "xalignat*") {
1701 if (mode != InsetMath::UNDECIDED_MODE) {
1702 error("bad math environment " + name);
1705 // ignore this for a while
1707 cell->push_back(MathAtom(new InsetMathHull(buf, hullXAlignAt)));
1708 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, !stared(name));
1711 else if (name == "xxalignat") {
1712 if (mode != InsetMath::UNDECIDED_MODE) {
1713 error("bad math environment " + name);
1716 // ignore this for a while
1718 cell->push_back(MathAtom(new InsetMathHull(buf, hullXXAlignAt)));
1719 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, !stared(name));
1722 else if (name == "multline" || name == "multline*") {
1723 if (mode != InsetMath::UNDECIDED_MODE) {
1724 error("bad math environment " + name);
1727 cell->push_back(MathAtom(new InsetMathHull(buf, hullMultline)));
1728 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, !stared(name));
1731 else if (name == "gather" || name == "gather*") {
1732 if (mode != InsetMath::UNDECIDED_MODE) {
1733 error("bad math environment " + name);
1736 cell->push_back(MathAtom(new InsetMathHull(buf, hullGather)));
1737 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, !stared(name));
1740 else if (latexkeys const * l = in_word_set(name)) {
1741 if (l->inset == "matrix") {
1742 cell->push_back(createInsetMath(name, buf));
1743 parse2(cell->back(), FLAG_END, mode, false);
1744 } else if (l->inset == "split") {
1745 docstring const valign = parse_verbatim_option() + 'c';
1746 cell->push_back(MathAtom(
1747 new InsetMathSplit(buf, name, (char)valign[0])));
1748 parse2(cell->back(), FLAG_END, mode, false);
1751 if (!(mode_ & Parse::QUIET)) {
1753 lyxerr << "found math environment `"
1755 << "' in symbols file with unsupported inset `"
1759 // create generic environment inset
1760 cell->push_back(MathAtom(new InsetMathEnv(buf, name)));
1761 parse(cell->back().nucleus()->cell(0), FLAG_END, mode);
1767 if (!(mode_ & Parse::QUIET)) {
1769 lyxerr << "found unknown math environment '"
1770 << to_utf8(name) << "'" << endl;
1772 // create generic environment inset
1773 cell->push_back(MathAtom(new InsetMathEnv(buf, name)));
1774 parse(cell->back().nucleus()->cell(0), FLAG_END, mode);
1778 else if (t.cs() == "kern") {
1783 Token const & t = getToken();
1787 while (num_tokens--)
1792 if (isValidLength(to_utf8(s)))
1796 cell->push_back(MathAtom(new InsetMathKern));
1798 cell->push_back(MathAtom(new InsetMathKern(s)));
1801 else if (t.cs() == "label") {
1802 // FIXME: This is swallowed in inline formulas
1803 docstring label = parse_verbatim_item();
1806 if (grid.asHullInset()) {
1807 grid.asHullInset()->label(cellrow, label);
1809 cell->push_back(createInsetMath(t.cs(), buf));
1810 cell->push_back(MathAtom(new InsetMathBrace(ar)));
1814 else if (t.cs() == "choose" || t.cs() == "over"
1815 || t.cs() == "atop" || t.cs() == "brace"
1816 || t.cs() == "brack") {
1817 MathAtom at = createInsetMath(t.cs(), buf);
1818 at.nucleus()->cell(0) = *cell;
1820 parse(at.nucleus()->cell(1), flags, mode);
1821 cell->push_back(at);
1825 else if (t.cs() == "color") {
1826 docstring const color = parse_verbatim_item();
1827 cell->push_back(MathAtom(new InsetMathColor(buf, true, color)));
1828 parse(cell->back().nucleus()->cell(0), flags, mode);
1832 else if (t.cs() == "textcolor") {
1833 docstring const color = parse_verbatim_item();
1834 cell->push_back(MathAtom(new InsetMathColor(buf, false, color)));
1835 parse(cell->back().nucleus()->cell(0), FLAG_ITEM, InsetMath::TEXT_MODE);
1838 else if (t.cs() == "normalcolor") {
1839 cell->push_back(createInsetMath(t.cs(), buf));
1840 parse(cell->back().nucleus()->cell(0), flags, mode);
1844 else if (t.cs() == "substack") {
1845 cell->push_back(createInsetMath(t.cs(), buf));
1846 parse2(cell->back(), FLAG_ITEM, mode, false);
1847 // Delete empty last row if present
1848 InsetMathGrid & subgrid =
1849 *(cell->back().nucleus()->asGridInset());
1850 if (subgrid.nrows() > 1)
1851 delEmptyLastRow(subgrid);
1854 else if (t.cs() == "xymatrix") {
1855 odocstringstream os;
1856 while (good() && nextToken().cat() != catBegin)
1857 os << getToken().asInput();
1858 cell->push_back(createInsetMath(t.cs() + os.str(), buf));
1859 parse2(cell->back(), FLAG_ITEM, mode, false);
1860 // Delete empty last row if present
1861 InsetMathGrid & subgrid =
1862 *(cell->back().nucleus()->asGridInset());
1863 if (subgrid.nrows() > 1)
1864 delEmptyLastRow(subgrid);
1867 else if (t.cs() == "Diagram") {
1868 odocstringstream os;
1869 while (good() && nextToken().cat() != catBegin)
1870 os << getToken().asInput();
1871 cell->push_back(createInsetMath(t.cs() + os.str(), buf));
1872 parse2(cell->back(), FLAG_ITEM, mode, false);
1875 else if (t.cs() == "framebox" || t.cs() == "makebox") {
1876 cell->push_back(createInsetMath(t.cs(), buf));
1877 parse(cell->back().nucleus()->cell(0), FLAG_OPTION, InsetMath::TEXT_MODE);
1878 parse(cell->back().nucleus()->cell(1), FLAG_OPTION, InsetMath::TEXT_MODE);
1879 parse(cell->back().nucleus()->cell(2), FLAG_ITEM, InsetMath::TEXT_MODE);
1882 else if (t.cs() == "tag") {
1883 if (nextToken().character() == '*') {
1885 cell->push_back(createInsetMath(t.cs() + '*', buf));
1887 cell->push_back(createInsetMath(t.cs(), buf));
1888 parse(cell->back().nucleus()->cell(0), FLAG_ITEM, InsetMath::TEXT_MODE);
1891 else if (t.cs() == "hspace") {
1892 bool const prot = nextToken().character() == '*';
1895 docstring const name = t.cs();
1896 docstring const arg = parse_verbatim_item();
1898 if (prot && arg == "\\fill")
1899 cell->push_back(MathAtom(new InsetMathSpace("hspace*{\\fill}", "")));
1900 else if (isValidLength(to_utf8(arg), &length))
1901 cell->push_back(MathAtom(new InsetMathSpace(length, prot)));
1903 // Since the Length class cannot use length variables
1904 // we must not create an InsetMathSpace.
1905 cell->push_back(MathAtom(new MathMacro(buf, name)));
1907 mathed_parse_cell(ar, '{' + arg + '}', mode_);
1912 else if (t.cs() == "smash") {
1914 if (nextToken().asInput() == "[") {
1915 // Since the phantom inset cannot handle optional arguments
1916 // other than b and t, we must not create an InsetMathPhantom
1917 // if opt is different from b and t (bug 8967).
1918 docstring const opt = parse_verbatim_option();
1919 if (opt == "t" || opt == "b") {
1920 cell->push_back(createInsetMath(t.cs() + opt, buf));
1921 parse(cell->back().nucleus()->cell(0), FLAG_ITEM, mode);
1923 docstring const arg = parse_verbatim_item();
1924 cell->push_back(MathAtom(new MathMacro(buf, t.cs())));
1926 mathed_parse_cell(ar, '[' + opt + ']', mode_);
1929 mathed_parse_cell(ar, '{' + arg + '}', mode_);
1934 cell->push_back(createInsetMath(t.cs(), buf));
1935 parse(cell->back().nucleus()->cell(0), FLAG_ITEM, mode);
1940 else if (t.cs() == "infer") {
1942 parse(ar, FLAG_OPTION, mode);
1943 cell->push_back(createInsetMath(t.cs(), buf));
1944 parse2(cell->back(), FLAG_ITEM, mode, false);
1948 else if (t.cs() == "lyxmathsym") {
1950 if (getToken().cat() != catBegin) {
1951 error("'{' expected in \\" + t.cs());
1956 CatCode cat = nextToken().cat();
1957 while (good() && (count || cat != catEnd)) {
1958 if (cat == catBegin)
1960 else if (cat == catEnd)
1962 cmd += getToken().asInput();
1963 cat = nextToken().cat();
1965 if (getToken().cat() != catEnd) {
1966 error("'}' expected in \\" + t.cs());
1972 cmd = Encodings::fromLaTeXCommand(cmd,
1973 Encodings::MATH_CMD | Encodings::TEXT_CMD,
1975 for (size_t i = 0; i < cmd.size(); ++i)
1976 cell->push_back(MathAtom(new InsetMathChar(cmd[i])));
1978 char_type c = rem[0];
1979 cell->push_back(MathAtom(new InsetMathChar(c)));
1980 cmd = rem.substr(1);
1984 } while (!cmd.empty());
1987 else if (!t.cs().empty()) {
1988 bool const no_mhchem =
1989 (t.cs() == "ce" || t.cs() == "cf")
1990 && buf && buf->params().use_package("mhchem") ==
1991 BufferParams::package_off;
1993 bool const is_user_macro = no_mhchem ||
1994 (buf && (mode_ & Parse::TRACKMACRO
1995 ? buf->usermacros.count(t.cs()) != 0
1996 : buf->getMacro(t.cs(), false) != 0));
1998 latexkeys const * l = in_word_set(t.cs());
1999 if (l && !is_user_macro) {
2000 if (l->inset == "big") {
2002 docstring const delim = getToken().asInput();
2003 if (InsetMathBig::isBigInsetDelim(delim))
2004 cell->push_back(MathAtom(
2005 new InsetMathBig(t.cs(), delim)));
2007 cell->push_back(createInsetMath(t.cs(), buf));
2012 else if (l->inset == "font") {
2013 cell->push_back(createInsetMath(t.cs(), buf));
2014 parse(cell->back().nucleus()->cell(0),
2015 FLAG_ITEM, asMode(mode, l->extra));
2018 else if (l->inset == "oldfont") {
2019 cell->push_back(createInsetMath(t.cs(), buf));
2020 parse(cell->back().nucleus()->cell(0),
2021 flags | FLAG_ALIGN, asMode(mode, l->extra));
2022 if (prevToken().cat() != catAlign &&
2023 prevToken().cs() != "\\")
2028 else if (l->inset == "style") {
2029 cell->push_back(createInsetMath(t.cs(), buf));
2030 parse(cell->back().nucleus()->cell(0),
2031 flags | FLAG_ALIGN, mode);
2032 if (prevToken().cat() != catAlign &&
2033 prevToken().cs() != "\\")
2039 MathAtom at = createInsetMath(t.cs(), buf);
2040 for (InsetMath::idx_type i = 0; i < at->nargs(); ++i)
2041 parse(at.nucleus()->cell(i),
2042 FLAG_ITEM, asMode(mode, l->extra));
2043 cell->push_back(at);
2048 bool is_unicode_symbol = false;
2049 if (mode == InsetMath::TEXT_MODE && !is_user_macro) {
2051 docstring cmd = prevToken().asInput();
2052 CatCode cat = nextToken().cat();
2053 if (cat == catBegin) {
2055 while (good() && (count || cat != catEnd)) {
2056 cat = nextToken().cat();
2057 cmd += getToken().asInput();
2059 if (cat == catBegin)
2061 else if (cat == catEnd)
2067 char_type c = Encodings::fromLaTeXCommand(cmd,
2068 Encodings::MATH_CMD | Encodings::TEXT_CMD,
2069 is_combining, termination);
2071 if (cat == catLetter)
2073 cmd += getToken().asInput();
2075 if (cat == catLetter)
2077 c = Encodings::fromLaTeXCommand(cmd,
2078 Encodings::MATH_CMD | Encodings::TEXT_CMD,
2079 is_combining, termination);
2083 if (nextToken().cat() == catBegin) {
2085 if (nextToken().cat() == catEnd) {
2091 while (nextToken().cat() == catSpace) {
2097 is_unicode_symbol = true;
2098 cell->push_back(MathAtom(new InsetMathChar(c)));
2100 while (num_tokens--)
2104 if (!is_unicode_symbol) {
2105 MathAtom at = is_user_macro ?
2106 MathAtom(new MathMacro(buf, t.cs()))
2107 : createInsetMath(t.cs(), buf);
2108 InsetMath::mode_type m = mode;
2109 //if (m == InsetMath::UNDECIDED_MODE)
2110 //lyxerr << "default creation: m1: " << m << endl;
2111 if (at->currentMode() != InsetMath::UNDECIDED_MODE)
2112 m = at->currentMode();
2113 //lyxerr << "default creation: m2: " << m << endl;
2114 InsetMath::idx_type start = 0;
2115 // this fails on \bigg[...\bigg]
2117 //parse(opt, FLAG_OPTION, InsetMath::VERBATIM_MODE);
2118 //if (!opt.empty()) {
2120 // at.nucleus()->cell(0) = opt;
2122 for (InsetMath::idx_type i = start; i < at->nargs(); ++i) {
2123 parse(at.nucleus()->cell(i), FLAG_ITEM, m);
2124 if (mode == InsetMath::MATH_MODE)
2127 cell->push_back(at);
2133 if (flags & FLAG_LEAVE) {
2134 flags &= ~FLAG_LEAVE;
2143 } // anonymous namespace
2146 // FIXME This will likely need some work.
2147 char const * latexkeys::MathMLtype() const
2149 if (extra == "mathord")
2155 bool mathed_parse_cell(MathData & ar, docstring const & str, Parse::flags f)
2157 return Parser(str, f, ar.buffer()).parse(ar, 0, f & Parse::TEXTMODE ?
2158 InsetMath::TEXT_MODE : InsetMath::MATH_MODE);
2162 bool mathed_parse_cell(MathData & ar, istream & is, Parse::flags f)
2164 return Parser(is, f, ar.buffer()).parse(ar, 0, f & Parse::TEXTMODE ?
2165 InsetMath::TEXT_MODE : InsetMath::MATH_MODE);
2169 bool mathed_parse_normal(Buffer * buf, MathAtom & t, docstring const & str,
2172 return Parser(str, f, buf).parse(t);
2176 bool mathed_parse_normal(Buffer * buf, MathAtom & t, Lexer & lex,
2179 return Parser(lex, f, buf).parse(t);
2183 bool mathed_parse_normal(InsetMathGrid & grid, docstring const & str,
2186 return Parser(str, f, &grid.buffer()).parse1(grid, 0, f & Parse::TEXTMODE ?
2187 InsetMath::TEXT_MODE : InsetMath::MATH_MODE, false);
2193 fill(theCatcode, theCatcode + 128, catOther);
2194 fill(theCatcode + 'a', theCatcode + 'z' + 1, catLetter);
2195 fill(theCatcode + 'A', theCatcode + 'Z' + 1, catLetter);
2197 theCatcode[int('\\')] = catEscape;
2198 theCatcode[int('{')] = catBegin;
2199 theCatcode[int('}')] = catEnd;
2200 theCatcode[int('$')] = catMath;
2201 theCatcode[int('&')] = catAlign;
2202 theCatcode[int('\n')] = catNewline;
2203 theCatcode[int('#')] = catParameter;
2204 theCatcode[int('^')] = catSuper;
2205 theCatcode[int('_')] = catSub;
2206 theCatcode[int(0x7f)] = catIgnore;
2207 theCatcode[int(' ')] = catSpace;
2208 theCatcode[int('\t')] = catSpace;
2209 theCatcode[int('\r')] = catNewline;
2210 theCatcode[int('~')] = catActive;
2211 theCatcode[int('%')] = catComment;