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 "InsetMathString.h"
63 #include "InsetMathTabular.h"
64 #include "MathMacroTemplate.h"
65 #include "MathFactory.h"
66 #include "MathMacroArgument.h"
67 #include "MathSupport.h"
70 #include "BufferParams.h"
74 #include "support/debug.h"
75 #include "support/convert.h"
76 #include "support/docstream.h"
88 InsetMath::mode_type asMode(InsetMath::mode_type oldmode, docstring const & str)
90 //lyxerr << "handling mode: '" << str << "'" << endl;
91 if (str == "mathmode")
92 return InsetMath::MATH_MODE;
93 if (str == "textmode" || str == "forcetext")
94 return InsetMath::TEXT_MODE;
99 bool stared(docstring const & s)
101 size_t const n = s.size();
102 return n && s[n - 1] == '*';
106 docstring const repl(docstring const & oldstr, char_type const c,
107 docstring const & macro, bool textmode = false)
113 for (i = 0, j = 0; i < oldstr.size(); ++i) {
114 if (c == oldstr[i]) {
115 newstr.append(oldstr, j, i - j);
116 newstr.append(macro);
118 if (macro.size() > 2 && j < oldstr.size())
119 newstr += (textmode && oldstr[j] == ' ' ? '\\' : ' ');
127 newstr.append(oldstr, j, i - j);
132 docstring escapeSpecialChars(docstring const & str, bool textmode)
134 docstring const backslash = textmode ? from_ascii("\\textbackslash")
135 : from_ascii("\\backslash");
136 docstring const caret = textmode ? from_ascii("\\textasciicircum")
137 : from_ascii("\\mathcircumflex");
138 docstring const tilde = textmode ? from_ascii("\\textasciitilde")
139 : from_ascii("\\sim");
141 return repl(repl(repl(repl(repl(repl(repl(repl(repl(repl(str,
142 '\\', backslash, textmode),
143 '^', caret, textmode),
144 '~', tilde, textmode),
145 '_', from_ascii("\\_")),
146 '$', from_ascii("\\$")),
147 '#', from_ascii("\\#")),
148 '&', from_ascii("\\&")),
149 '%', from_ascii("\\%")),
150 '{', from_ascii("\\{")),
151 '}', from_ascii("\\}"));
156 * Add the row \p cellrow to \p grid.
157 * \returns wether the row could be added. Adding a row can fail for
158 * environments like "equation" that have a fixed number of rows.
160 bool addRow(InsetMathGrid & grid, InsetMathGrid::row_type & cellrow,
161 docstring const & vskip, bool allow_newpage_ = true)
164 if (cellrow == grid.nrows()) {
165 //lyxerr << "adding row " << cellrow << endl;
166 grid.addRow(cellrow - 1);
167 if (cellrow == grid.nrows()) {
168 // We can't add a row to this grid, so let's
169 // append the content of this cell to the previous
171 // This does not happen in well formed .lyx files,
172 // but LyX versions 1.3.x and older could create
173 // such files and tex2lyx can still do that.
175 lyxerr << "ignoring extra row";
177 lyxerr << " with extra space " << to_utf8(vskip);
179 lyxerr << " with no page break allowed";
180 lyxerr << '.' << endl;
184 grid.vcrskip(Length(to_utf8(vskip)), cellrow - 1);
185 grid.rowinfo(cellrow - 1).allow_newpage_ = allow_newpage_;
191 * Add the column \p cellcol to \p grid.
192 * \returns wether the column could be added. Adding a column can fail for
193 * environments like "eqnarray" that have a fixed number of columns.
195 bool addCol(InsetMathGrid & grid, InsetMathGrid::col_type & cellcol)
198 if (cellcol == grid.ncols()) {
199 //lyxerr << "adding column " << cellcol << endl;
200 grid.addCol(cellcol);
201 if (cellcol == grid.ncols()) {
202 // We can't add a column to this grid, so let's
203 // append the content of this cell to the previous
205 // This does not happen in well formed .lyx files,
206 // but LyX versions 1.3.x and older could create
207 // such files and tex2lyx can still do that.
209 lyxerr << "ignoring extra column." << endl;
218 * Check whether the last row is empty and remove it if yes.
219 * Otherwise the following code
227 * will result in a grid with 3 rows (+ the dummy row that is always present),
228 * because the last '\\' opens a new row.
229 * Note that this is only needed for inner-hull grid types, such as array
230 * or aligned, but not for outer-hull grid types, such as eqnarray or align.
232 void delEmptyLastRow(InsetMathGrid & grid)
234 InsetMathGrid::row_type const row = grid.nrows() - 1;
235 for (InsetMathGrid::col_type col = 0; col < grid.ncols(); ++col) {
236 if (!grid.cell(grid.index(row, col)).empty())
239 // Copy the row information of the empty row (which would contain the
240 // last hline in the example above) to the dummy row and delete the
242 grid.rowinfo(row + 1) = grid.rowinfo(row);
248 * Tell whether the environment name corresponds to an inner-hull grid type.
250 bool innerHull(docstring const & name)
252 // For [bB]matrix, [vV]matrix, and pmatrix we can check the suffix only
253 return name == "array" || name == "cases" || name == "aligned"
254 || name == "alignedat" || name == "gathered" || name == "split"
255 || name == "subarray" || name == "tabular" || name == "matrix"
256 || name == "smallmatrix" || name.substr(1) == "matrix";
260 // These are TeX's catcodes
262 catEscape, // 0 backslash
272 catSpace, // 10 space
273 catLetter, // 11 a-zA-Z
274 catOther, // 12 none of the above
277 catInvalid // 15 <delete>
280 CatCode theCatcode[128];
283 inline CatCode catcode(char_type c)
285 /* The only characters that are not catOther lie in the pure ASCII
286 * range. Therefore theCatcode has only 128 entries.
287 * TeX itself deals with 8bit characters, so if needed this table
288 * could be enlarged to 256 entries.
289 * Any larger value does not make sense, since the fact that we use
290 * unicode internally does not change Knuth's TeX engine.
291 * Apart from that a table for the full 21bit UCS4 range would waste
292 * too much memory. */
296 return theCatcode[c];
301 FLAG_ALIGN = 1 << 0, // next & or \\ ends the parsing process
302 FLAG_BRACE_LAST = 1 << 1, // next closing brace ends the parsing
303 FLAG_RIGHT = 1 << 2, // next \\right ends the parsing process
304 FLAG_END = 1 << 3, // next \\end ends the parsing process
305 FLAG_BRACK_LAST = 1 << 4, // next closing bracket ends the parsing
306 FLAG_TEXTMODE = 1 << 5, // we are in a box
307 FLAG_ITEM = 1 << 6, // read a (possibly braced) token
308 FLAG_LEAVE = 1 << 7, // leave the loop at the end
309 FLAG_SIMPLE = 1 << 8, // next $ leaves the loop
310 FLAG_EQUATION = 1 << 9, // next \] leaves the loop
311 FLAG_SIMPLE2 = 1 << 10, // next \) leaves the loop
312 FLAG_OPTION = 1 << 11, // read [...] style option
313 FLAG_BRACED = 1 << 12 // read {...} style argument
318 // Helper class for parsing
324 Token() : cs_(), char_(0), cat_(catIgnore) {}
326 Token(char_type c, CatCode cat) : cs_(), char_(c), cat_(cat) {}
328 explicit Token(docstring const & cs) : cs_(cs), char_(0), cat_(catIgnore) {}
331 docstring const & cs() const { return cs_; }
333 CatCode cat() const { return cat_; }
335 char_type character() const { return char_; }
337 docstring asString() const { return cs_.size() ? cs_ : docstring(1, char_); }
339 docstring asInput() const { return cs_.size() ? '\\' + cs_ : docstring(1, char_); }
351 ostream & operator<<(ostream & os, Token const & t)
354 docstring const & cs = t.cs();
355 // FIXME: For some strange reason, the stream operator instanciate
356 // a new Token before outputting the contents of t.cs().
357 // Because of this the line
359 // below becomes recursive.
360 // In order to avoid that we return early:
363 os << '\\' << to_utf8(cs);
365 else if (t.cat() == catLetter)
368 os << '[' << t.character() << ',' << t.cat() << ']';
376 typedef InsetMath::mode_type mode_type;
378 typedef Parse::flags parse_mode;
381 Parser(Lexer & lex, parse_mode mode, Buffer * buf);
382 /// Only use this for reading from .lyx file format, for the reason
383 /// see Parser::tokenize(istream &).
384 Parser(istream & is, parse_mode mode, Buffer * buf);
386 Parser(docstring const & str, parse_mode mode, Buffer * buf);
389 bool parse(MathAtom & at);
391 bool parse(MathData & array, unsigned flags, mode_type mode);
393 bool parse1(InsetMathGrid & grid, unsigned flags, mode_type mode,
396 MathData parse(unsigned flags, mode_type mode);
398 int lineno() const { return lineno_; }
404 void parse2(MathAtom & at, unsigned flags, mode_type mode, bool numbered);
405 /// get arg delimited by 'left' and 'right'
406 docstring getArg(char_type left, char_type right);
410 void error(string const & msg);
411 void error(docstring const & msg) { error(to_utf8(msg)); }
412 /// dump contents to screen
414 /// Only use this for reading from .lyx file format (see
415 /// implementation for reason)
416 void tokenize(istream & is);
418 void tokenize(docstring const & s);
420 void skipSpaceTokens(idocstream & is, char_type c);
422 void push_back(Token const & t);
426 Token const & prevToken() const;
428 Token const & nextToken() const;
430 Token const & getToken();
431 /// skips spaces if any
434 void lex(docstring const & s);
438 docstring parse_verbatim_item();
440 docstring parse_verbatim_option();
445 vector<Token> tokens_;
448 /// Stack of active environments
449 vector<docstring> environments_;
459 Parser::Parser(Lexer & lexer, parse_mode mode, Buffer * buf)
460 : lineno_(lexer.lineNumber()), pos_(0), mode_(mode), success_(true),
463 tokenize(lexer.getStream());
468 Parser::Parser(istream & is, parse_mode mode, Buffer * buf)
469 : lineno_(0), pos_(0), mode_(mode), success_(true), buffer_(buf)
475 Parser::Parser(docstring const & str, parse_mode mode, Buffer * buf)
476 : lineno_(0), pos_(0), mode_(mode), success_(true), buffer_(buf)
482 void Parser::push_back(Token const & t)
484 tokens_.push_back(t);
488 void Parser::pop_back()
494 Token const & Parser::prevToken() const
496 static const Token dummy;
497 return pos_ > 0 ? tokens_[pos_ - 1] : dummy;
501 Token const & Parser::nextToken() const
503 static const Token dummy;
504 return good() ? tokens_[pos_] : dummy;
508 Token const & Parser::getToken()
510 static const Token dummy;
511 //lyxerr << "looking at token " << tokens_[pos_] << " pos: " << pos_ << endl;
512 return good() ? tokens_[pos_++] : dummy;
516 void Parser::skipSpaces()
518 while (nextToken().cat() == catSpace || nextToken().cat() == catNewline)
523 void Parser::putback()
529 bool Parser::good() const
531 return pos_ < tokens_.size();
535 char_type Parser::getChar()
538 error("The input stream is not well...");
542 return tokens_[pos_++].character();
546 docstring Parser::getArg(char_type left, char_type right)
551 char_type c = getChar();
556 while ((c = getChar()) != right && good())
563 void Parser::skipSpaceTokens(idocstream & is, char_type c)
565 // skip trailing spaces
566 while (catcode(c) == catSpace || catcode(c) == catNewline)
569 //lyxerr << "putting back: " << c << endl;
574 void Parser::tokenize(istream & is)
576 // eat everything up to the next \end_inset or end of stream
577 // and store it in s for further tokenization
582 if (s.size() >= 10 && s.substr(s.size() - 10) == "\\end_inset") {
583 s = s.substr(0, s.size() - 10);
587 // Remove the space after \end_inset
588 if (is.get(c) && c != ' ')
592 tokenize(from_utf8(s));
596 void Parser::tokenize(docstring const & buffer)
598 idocstringstream is(mode_ & Parse::VERBATIM
599 ? escapeSpecialChars(buffer, mode_ & Parse::TEXTMODE)
600 : buffer, ios::in | ios::binary);
604 //lyxerr << "reading c: " << c << endl;
606 switch (catcode(c)) {
610 if (catcode(c) == catNewline)
611 ; //push_back(Token("par"));
613 push_back(Token('\n', catNewline));
621 while (is.get(c) && catcode(c) != catNewline)
631 error("unexpected end of input");
636 if (catcode(c) == catLetter) {
638 while (is.get(c) && catcode(c) == catLetter)
640 skipSpaceTokens(is, c);
649 push_back(Token(c, catcode(c)));
651 skipSpaceTokens(is, c);
656 if (!(mode_ & Parse::QUIET))
657 lyxerr << "ignoring a char: " << int(c) << endl;
662 push_back(Token(c, catcode(c)));
672 void Parser::dump() const
674 lyxerr << "\nTokens: ";
675 for (unsigned i = 0; i < tokens_.size(); ++i) {
678 lyxerr << tokens_[i];
680 lyxerr << " pos: " << pos_ << endl;
684 void Parser::error(string const & msg)
687 if (!(mode_ & Parse::QUIET)) {
688 lyxerr << "Line ~" << lineno_ << ": Math parse error: "
695 bool Parser::parse(MathAtom & at)
698 MathData ar(buffer_);
699 parse(ar, false, InsetMath::UNDECIDED_MODE);
700 if (ar.size() != 1 || ar.front()->getType() == hullNone) {
701 if (!(mode_ & Parse::QUIET))
702 lyxerr << "unusual contents found: " << ar << endl;
703 at = MathAtom(new InsetMathPar(buffer_, ar));
704 //if (at->nargs() > 0)
705 // at.nucleus()->cell(0) = ar;
707 // lyxerr << "unusual contents found: " << ar << endl;
715 docstring Parser::parse_verbatim_option()
719 if (nextToken().character() == '[') {
720 Token t = getToken();
721 for (Token t = getToken(); t.character() != ']' && good(); t = getToken()) {
722 if (t.cat() == catBegin) {
724 res += '{' + parse_verbatim_item() + '}';
733 docstring Parser::parse_verbatim_item()
737 if (nextToken().cat() == catBegin) {
738 Token t = getToken();
739 for (Token t = getToken(); t.cat() != catEnd && good(); t = getToken()) {
740 if (t.cat() == catBegin) {
742 res += '{' + parse_verbatim_item() + '}';
752 MathData Parser::parse(unsigned flags, mode_type mode)
754 MathData ar(buffer_);
755 parse(ar, flags, mode);
760 bool Parser::parse(MathData & array, unsigned flags, mode_type mode)
762 InsetMathGrid grid(buffer_, 1, 1);
763 parse1(grid, flags, mode, false);
764 array = grid.cell(0);
769 void Parser::parse2(MathAtom & at, const unsigned flags, const mode_type mode,
772 parse1(*(at.nucleus()->asGridInset()), flags, mode, numbered);
776 bool Parser::parse1(InsetMathGrid & grid, unsigned flags,
777 const mode_type mode, const bool numbered)
780 InsetMathGrid::row_type cellrow = 0;
781 InsetMathGrid::col_type cellcol = 0;
782 MathData * cell = &grid.cell(grid.index(cellrow, cellcol));
783 Buffer * buf = buffer_;
785 if (grid.asHullInset())
786 grid.asHullInset()->numbered(cellrow, numbered);
789 //lyxerr << " flags: " << flags << endl;
790 //lyxerr << " mode: " << mode << endl;
791 //lyxerr << "grid: " << grid << endl;
794 Token const & t = getToken();
797 lyxerr << "t: " << t << " flags: " << flags << endl;
798 lyxerr << "mode: " << mode << endl;
803 if (flags & FLAG_ITEM) {
805 if (t.cat() == catBegin) {
806 // skip the brace and collect everything to the next matching
808 parse1(grid, FLAG_BRACE_LAST, mode, numbered);
812 // handle only this single token, leave the loop if done
817 if (flags & FLAG_BRACED) {
818 if (t.cat() == catSpace)
821 if (t.cat() != catBegin) {
822 error("opening brace expected");
826 // skip the brace and collect everything to the next matching
828 flags = FLAG_BRACE_LAST;
832 if (flags & FLAG_OPTION) {
833 if (t.cat() == catOther && t.character() == '[') {
835 parse(ar, FLAG_BRACK_LAST, mode);
838 // no option found, put back token and we are done
847 if (t.cat() == catMath) {
848 if (mode != InsetMath::MATH_MODE) {
849 // we are inside some text mode thingy, so opening new math is allowed
850 Token const & n = getToken();
851 if (n.cat() == catMath) {
852 // TeX's $$...$$ syntax for displayed math
853 if (mode == InsetMath::UNDECIDED_MODE) {
854 cell->push_back(MathAtom(new InsetMathHull(buf, hullEquation)));
855 parse2(cell->back(), FLAG_SIMPLE, InsetMath::MATH_MODE, false);
856 getToken(); // skip the second '$' token
858 // This is not an outer hull and display math is
859 // not allowed inside text mode environments.
860 error("bad math environment");
864 // simple $...$ stuff
866 if (mode == InsetMath::UNDECIDED_MODE) {
867 cell->push_back(MathAtom(new InsetMathHull(buf, hullSimple)));
868 parse2(cell->back(), FLAG_SIMPLE, InsetMath::MATH_MODE, false);
870 // Don't create nested math hulls (bug #5392)
871 cell->push_back(MathAtom(new InsetMathEnsureMath(buf)));
872 parse(cell->back().nucleus()->cell(0), FLAG_SIMPLE, InsetMath::MATH_MODE);
877 else if (flags & FLAG_SIMPLE) {
878 // this is the end of the formula
883 Token const & n = getToken();
884 if (n.cat() == catMath) {
885 error("something strange in the parser");
888 // This is inline math ($...$), but the parser thinks we are
889 // already in math mode and latex would issue an error, unless we
890 // are inside a text mode user macro. We have no way to tell, so
891 // let's play safe by using \ensuremath, as it will work in any case.
893 cell->push_back(MathAtom(new InsetMathEnsureMath(buf)));
894 parse(cell->back().nucleus()->cell(0), FLAG_SIMPLE, InsetMath::MATH_MODE);
899 else if (t.cat() == catLetter)
900 cell->push_back(MathAtom(new InsetMathChar(t.character())));
902 else if (t.cat() == catSpace && mode != InsetMath::MATH_MODE) {
903 if (cell->empty() || cell->back()->getChar() != ' ')
904 cell->push_back(MathAtom(new InsetMathChar(t.character())));
907 else if (t.cat() == catNewline && mode != InsetMath::MATH_MODE) {
908 if (cell->empty() || cell->back()->getChar() != ' ')
909 cell->push_back(MathAtom(new InsetMathChar(' ')));
912 else if (t.cat() == catParameter) {
913 Token const & n = getToken();
914 cell->push_back(MathAtom(new MathMacroArgument(n.character()-'0')));
917 else if (t.cat() == catActive)
918 cell->push_back(MathAtom(new InsetMathSpace(string(1, t.character()), "")));
920 else if (t.cat() == catBegin) {
922 parse(ar, FLAG_BRACE_LAST, mode);
923 // do not create a BraceInset if they were written by LyX
924 // this helps to keep the annoyance of "a choose b" to a minimum
925 if (ar.size() == 1 && ar[0]->extraBraces())
928 cell->push_back(MathAtom(new InsetMathBrace(ar)));
931 else if (t.cat() == catEnd) {
932 if (flags & FLAG_BRACE_LAST)
934 error("found '}' unexpectedly");
935 //LASSERT(false, /**/);
936 //add(cell, '}', LM_TC_TEX);
939 else if (t.cat() == catAlign) {
940 //lyxerr << " column now " << (cellcol + 1)
941 // << " max: " << grid.ncols() << endl;
942 if (flags & FLAG_ALIGN)
944 if (addCol(grid, cellcol))
945 cell = &grid.cell(grid.index(cellrow, cellcol));
948 else if (t.cat() == catSuper || t.cat() == catSub) {
949 bool up = (t.cat() == catSuper);
950 // we need no new script inset if the last thing was a scriptinset,
951 // which has that script already not the same script already
953 cell->push_back(MathAtom(new InsetMathScript(buf, up)));
954 else if (cell->back()->asScriptInset() &&
955 !cell->back()->asScriptInset()->has(up))
956 cell->back().nucleus()->asScriptInset()->ensure(up);
957 else if (cell->back()->asScriptInset())
958 cell->push_back(MathAtom(new InsetMathScript(buf, up)));
960 cell->back() = MathAtom(new InsetMathScript(buf, cell->back(), up));
961 InsetMathScript * p = cell->back().nucleus()->asScriptInset();
962 // special handling of {}-bases
963 // Here we could remove the brace inset for things
964 // like {a'}^2 and add the braces back in
965 // InsetMathScript::write().
966 // We do not do it, since it is not possible to detect
967 // reliably whether the braces are needed because the
968 // nucleus contains more than one symbol, or whether
969 // they are needed for unknown commands like \xx{a}_0
970 // or \yy{a}{b}_0. This was done in revision 14819
971 // in an unreliable way. See this thread
972 // http://www.mail-archive.com/lyx-devel%40lists.lyx.org/msg104917.html
974 // However, we remove empty braces because they look
975 // ugly on screen and we are sure that they were added
976 // by the write() method (and will be re-added on save).
977 if (p->nuc().size() == 1 &&
978 p->nuc().back()->asBraceInset() &&
979 p->nuc().back()->asBraceInset()->cell(0).empty())
982 parse(p->cell(p->idxOfScript(up)), FLAG_ITEM, mode);
989 else if (t.character() == ']' && (flags & FLAG_BRACK_LAST)) {
990 //lyxerr << "finished reading option" << endl;
994 else if (t.cat() == catOther) {
995 char_type c = t.character();
996 if (isAsciiOrMathAlpha(c)
997 || mode_ & Parse::VERBATIM
998 || !(mode_ & Parse::USETEXT)
999 || mode == InsetMath::TEXT_MODE) {
1000 cell->push_back(MathAtom(new InsetMathChar(c)));
1002 MathAtom at = createInsetMath("text", buf);
1003 at.nucleus()->cell(0).push_back(MathAtom(new InsetMathChar(c)));
1004 while (nextToken().cat() == catOther
1005 && !isAsciiOrMathAlpha(nextToken().character())) {
1006 c = getToken().character();
1007 at.nucleus()->cell(0).push_back(MathAtom(new InsetMathChar(c)));
1009 cell->push_back(at);
1013 else if (t.cat() == catComment) {
1016 Token const & t = getToken();
1017 if (t.cat() == catNewline)
1021 cell->push_back(MathAtom(new InsetMathComment(buf, s)));
1026 // control sequences
1029 else if (t.cs() == "lyxlock") {
1031 cell->back().nucleus()->lock(true);
1034 else if ((t.cs() == "global" && nextToken().cs() == "def") ||
1036 if (t.cs() == "global")
1040 docstring name = getToken().cs();
1045 while (good() && nextToken().cat() != catBegin) {
1046 pars += getToken().cs();
1053 parse(def, FLAG_ITEM, InsetMath::UNDECIDED_MODE);
1055 // is a version for display attached?
1058 if (nextToken().cat() == catBegin)
1059 parse(display, FLAG_ITEM, InsetMath::MATH_MODE);
1061 cell->push_back(MathAtom(new MathMacroTemplate(buf,
1062 name, nargs, 0, MacroTypeDef,
1063 vector<MathData>(), def, display)));
1065 if (buf && (mode_ & Parse::TRACKMACRO))
1066 buf->usermacros.insert(name);
1069 else if (t.cs() == "newcommand" ||
1070 t.cs() == "renewcommand" ||
1071 t.cs() == "newlyxcommand") {
1073 if (getToken().cat() != catBegin) {
1074 error("'{' in \\newcommand expected (1) ");
1077 docstring name = getToken().cs();
1078 if (getToken().cat() != catEnd) {
1079 error("'}' in \\newcommand expected");
1084 docstring const arg = getArg('[', ']');
1087 nargs = convert<int>(arg);
1089 // optional argument given?
1092 vector<MathData> optionalValues;
1093 while (nextToken().character() == '[') {
1095 optionalValues.push_back(MathData());
1096 parse(optionalValues[optionals], FLAG_BRACK_LAST, mode);
1101 parse(def, FLAG_ITEM, InsetMath::UNDECIDED_MODE);
1103 // is a version for display attached?
1106 if (nextToken().cat() == catBegin)
1107 parse(display, FLAG_ITEM, InsetMath::MATH_MODE);
1109 cell->push_back(MathAtom(new MathMacroTemplate(buf,
1110 name, nargs, optionals, MacroTypeNewcommand,
1111 optionalValues, def, display)));
1113 if (buf && (mode_ & Parse::TRACKMACRO))
1114 buf->usermacros.insert(name);
1117 else if (t.cs() == "newcommandx" ||
1118 t.cs() == "renewcommandx") {
1119 // \newcommandx{\foo}[2][usedefault, addprefix=\global,1=default]{#1,#2}
1122 if (nextToken().cat() == catBegin) {
1124 name = getToken().cs();
1125 if (getToken().cat() != catEnd) {
1126 error("'}' in \\newcommandx expected");
1130 name = getToken().cs();
1133 docstring const arg = getArg('[', ']');
1135 error("[num] in \\newcommandx expected");
1138 int nargs = convert<int>(arg);
1142 vector<MathData> optionalValues;
1143 if (nextToken().character() == '[') {
1147 // handle 'opt=value' options, separated by ','.
1149 while (nextToken().character() != ']' && good()) {
1150 if (nextToken().character() >= '1'
1151 && nextToken().character() <= '9') {
1152 // optional value -> get parameter number
1153 int n = getChar() - '0';
1155 error("Arity of \\newcommandx too low "
1156 "for given optional parameter.");
1161 if (getToken().character() != '=') {
1162 error("'=' and optional parameter value "
1163 "expected for \\newcommandx");
1168 int optNum = max(size_t(n), optionalValues.size());
1169 optionalValues.resize(optNum);
1170 optionalValues[n - 1].clear();
1171 while (nextToken().character() != ']'
1172 && nextToken().character() != ',') {
1174 parse(data, FLAG_ITEM, InsetMath::UNDECIDED_MODE);
1175 optionalValues[n - 1].append(data);
1177 optionals = max(n, optionals);
1178 } else if (nextToken().cat() == catLetter) {
1179 // we in fact ignore every non-optional
1184 while (nextToken().cat() == catLetter)
1190 if (nextToken().character() == '=') {
1192 while (nextToken().character() != ']'
1193 && nextToken().character() != ',')
1194 parse(value, FLAG_ITEM,
1195 InsetMath::UNDECIDED_MODE);
1198 error("option for \\newcommandx expected");
1204 if (nextToken().character() == ',') {
1207 } else if (nextToken().character() != ']') {
1208 error("Expecting ',' or ']' in options "
1209 "of \\newcommandx");
1222 parse(def, FLAG_ITEM, InsetMath::UNDECIDED_MODE);
1224 // is a version for display attached?
1227 if (nextToken().cat() == catBegin)
1228 parse(display, FLAG_ITEM, InsetMath::MATH_MODE);
1230 cell->push_back(MathAtom(new MathMacroTemplate(buf,
1231 name, nargs, optionals, MacroTypeNewcommandx,
1232 optionalValues, def, display)));
1234 if (buf && (mode_ & Parse::TRACKMACRO))
1235 buf->usermacros.insert(name);
1238 else if (t.cs() == "(") {
1239 cell->push_back(MathAtom(new InsetMathEnsureMath(buf)));
1240 parse(cell->back().nucleus()->cell(0), FLAG_SIMPLE2, InsetMath::MATH_MODE);
1243 else if (t.cs() == "[") {
1244 if (mode != InsetMath::UNDECIDED_MODE) {
1245 error("bad math environment");
1248 cell->push_back(MathAtom(new InsetMathHull(buf, hullEquation)));
1249 parse2(cell->back(), FLAG_EQUATION, InsetMath::MATH_MODE, false);
1252 else if (t.cs() == "protect")
1253 // ignore \\protect, will hopefully be re-added during output
1256 else if (t.cs() == "end") {
1257 if (flags & FLAG_END) {
1258 // eat environment name
1259 docstring const name = getArg('{', '}');
1260 if (environments_.empty())
1261 error("'found \\end{" + name +
1262 "}' without matching '\\begin{" +
1264 else if (name != environments_.back())
1265 error("'\\end{" + name +
1266 "}' does not match '\\begin{" +
1267 environments_.back() + "}'");
1269 environments_.pop_back();
1270 // Delete empty last row in matrix
1272 // If you abuse InsetMathGrid for
1273 // non-matrix like structures you
1274 // probably need to refine this test.
1275 // Right now we only have to test for
1276 // single line hull insets.
1277 if (grid.nrows() > 1 && innerHull(name))
1278 delEmptyLastRow(grid);
1282 error("found 'end' unexpectedly");
1285 else if (t.cs() == ")") {
1286 if (flags & FLAG_SIMPLE2)
1288 error("found '\\)' unexpectedly");
1291 else if (t.cs() == "]") {
1292 if (flags & FLAG_EQUATION)
1294 error("found '\\]' unexpectedly");
1297 else if (t.cs() == "\\") {
1298 if (flags & FLAG_ALIGN)
1301 if (nextToken().asInput() == "*") {
1303 added = addRow(grid, cellrow, docstring(), false);
1305 added = addRow(grid, cellrow, getArg('[', ']'));
1307 error("missing token after \\\\");
1310 if (grid.asHullInset())
1311 grid.asHullInset()->numbered(
1313 cell = &grid.cell(grid.index(cellrow,
1319 else if (t.cs() == "multicolumn") {
1320 // extract column count and insert dummy cells
1322 parse(count, FLAG_ITEM, mode);
1324 if (!extractNumber(count, cols)) {
1326 lyxerr << " can't extract number of cells from " << count << endl;
1328 // resize the table if necessary
1329 for (int i = 0; i < cols; ++i) {
1330 if (addCol(grid, cellcol)) {
1331 cell = &grid.cell(grid.index(
1333 // mark this as dummy
1334 grid.cellinfo(grid.index(
1335 cellrow, cellcol)).dummy_ = true;
1338 // the last cell is the real thing, not a dummy
1339 grid.cellinfo(grid.index(cellrow, cellcol)).dummy_ = false;
1341 // read special alignment
1343 parse(align, FLAG_ITEM, mode);
1344 //grid.cellinfo(grid.index(cellrow, cellcol)).align_ = extractString(align);
1346 // parse the remaining contents into the "real" cell
1347 parse(*cell, FLAG_ITEM, mode);
1351 else if (t.cs() == "limits" || t.cs() == "nolimits") {
1352 CatCode const cat = nextToken().cat();
1353 if (cat == catSuper || cat == catSub)
1354 limits = t.cs() == "limits" ? 1 : -1;
1356 MathAtom at = createInsetMath(t.cs(), buf);
1357 cell->push_back(at);
1361 else if (t.cs() == "nonumber") {
1362 if (grid.asHullInset())
1363 grid.asHullInset()->numbered(cellrow, false);
1366 else if (t.cs() == "number") {
1367 if (grid.asHullInset())
1368 grid.asHullInset()->numbered(cellrow, true);
1371 else if (t.cs() == "hline") {
1372 grid.rowinfo(cellrow).lines_ ++;
1375 else if (t.cs() == "sqrt") {
1377 parse(ar, FLAG_OPTION, mode);
1379 cell->push_back(MathAtom(new InsetMathRoot(buf)));
1380 cell->back().nucleus()->cell(0) = ar;
1381 parse(cell->back().nucleus()->cell(1), FLAG_ITEM, mode);
1383 cell->push_back(MathAtom(new InsetMathSqrt(buf)));
1384 parse(cell->back().nucleus()->cell(0), FLAG_ITEM, mode);
1388 else if (t.cs() == "cancelto") {
1390 parse(ar, FLAG_ITEM, mode);
1391 cell->push_back(MathAtom(new InsetMathCancelto(buf)));
1392 cell->back().nucleus()->cell(1) = ar;
1393 parse(cell->back().nucleus()->cell(0), FLAG_ITEM, mode);
1396 else if (t.cs() == "unit") {
1397 // Allowed formats \unit[val]{unit}
1399 parse(ar, FLAG_OPTION, mode);
1401 cell->push_back(MathAtom(new InsetMathFrac(buf, InsetMathFrac::UNIT)));
1402 cell->back().nucleus()->cell(0) = ar;
1403 parse(cell->back().nucleus()->cell(1), FLAG_ITEM, mode);
1405 cell->push_back(MathAtom(new InsetMathFrac(buf, InsetMathFrac::UNIT, 1)));
1406 parse(cell->back().nucleus()->cell(0), FLAG_ITEM, mode);
1410 else if (t.cs() == "unitfrac") {
1411 // Here allowed formats are \unitfrac[val]{num}{denom}
1413 parse(ar, FLAG_OPTION, mode);
1415 cell->push_back(MathAtom(new InsetMathFrac(buf, InsetMathFrac::UNITFRAC, 3)));
1416 cell->back().nucleus()->cell(2) = ar;
1418 cell->push_back(MathAtom(new InsetMathFrac(buf, InsetMathFrac::UNITFRAC)));
1420 parse(cell->back().nucleus()->cell(0), FLAG_ITEM, mode);
1421 parse(cell->back().nucleus()->cell(1), FLAG_ITEM, mode);
1424 else if (t.cs() == "cfrac") {
1425 // allowed formats are \cfrac[pos]{num}{denom}
1426 docstring const arg = getArg('[', ']');
1427 //lyxerr << "got so far: '" << arg << "'" << endl;
1429 cell->push_back(MathAtom(new InsetMathFrac(buf, InsetMathFrac::CFRACLEFT)));
1430 else if (arg == "r")
1431 cell->push_back(MathAtom(new InsetMathFrac(buf, InsetMathFrac::CFRACRIGHT)));
1432 else if (arg.empty() || arg == "c")
1433 cell->push_back(MathAtom(new InsetMathFrac(buf, InsetMathFrac::CFRAC)));
1435 error("found invalid optional argument");
1438 parse(cell->back().nucleus()->cell(0), FLAG_ITEM, mode);
1439 parse(cell->back().nucleus()->cell(1), FLAG_ITEM, mode);
1442 else if (t.cs() == "xrightarrow" || t.cs() == "xleftarrow") {
1443 cell->push_back(createInsetMath(t.cs(), buf));
1444 parse(cell->back().nucleus()->cell(1), FLAG_OPTION, mode);
1445 parse(cell->back().nucleus()->cell(0), FLAG_ITEM, mode);
1448 else if (t.cs() == "ref" || t.cs() == "eqref" || t.cs() == "prettyref"
1449 || t.cs() == "pageref" || t.cs() == "vpageref" || t.cs() == "vref") {
1450 cell->push_back(MathAtom(new InsetMathRef(buf, t.cs())));
1451 docstring const opt = parse_verbatim_option();
1452 docstring const ref = parse_verbatim_item();
1454 cell->back().nucleus()->cell(1).push_back(
1455 MathAtom(new InsetMathString(opt)));
1457 cell->back().nucleus()->cell(0).push_back(
1458 MathAtom(new InsetMathString(ref)));
1461 else if (t.cs() == "left") {
1463 Token const & tl = getToken();
1464 // \| and \Vert are equivalent, and InsetMathDelim
1466 // FIXME: fix this in InsetMathDelim itself!
1467 docstring const l = tl.cs() == "|" ? from_ascii("Vert") : tl.asString();
1469 parse(ar, FLAG_RIGHT, mode);
1473 Token const & tr = getToken();
1474 docstring const r = tr.cs() == "|" ? from_ascii("Vert") : tr.asString();
1475 cell->push_back(MathAtom(new InsetMathDelim(buf, l, r, ar)));
1478 else if (t.cs() == "right") {
1479 if (flags & FLAG_RIGHT)
1481 //lyxerr << "got so far: '" << cell << "'" << endl;
1482 error("Unmatched right delimiter");
1486 else if (t.cs() == "begin") {
1487 docstring const name = getArg('{', '}');
1488 environments_.push_back(name);
1490 if (name == "array" || name == "subarray") {
1491 docstring const valign = parse_verbatim_option() + 'c';
1492 docstring const halign = parse_verbatim_item();
1493 cell->push_back(MathAtom(new InsetMathArray(buf, name,
1494 InsetMathGrid::guessColumns(halign), 1, (char)valign[0], halign)));
1495 parse2(cell->back(), FLAG_END, mode, false);
1498 else if (name == "tabular") {
1499 docstring const valign = parse_verbatim_option() + 'c';
1500 docstring const halign = parse_verbatim_item();
1501 cell->push_back(MathAtom(new InsetMathTabular(buf, name,
1502 InsetMathGrid::guessColumns(halign), 1, (char)valign[0], halign)));
1503 parse2(cell->back(), FLAG_END, InsetMath::TEXT_MODE, false);
1506 else if (name == "split" || name == "cases") {
1507 cell->push_back(createInsetMath(name, buf));
1508 parse2(cell->back(), FLAG_END, mode, false);
1511 else if (name == "alignedat") {
1512 docstring const valign = parse_verbatim_option() + 'c';
1513 // ignore this for a while
1515 cell->push_back(MathAtom(new InsetMathSplit(buf, name, (char)valign[0])));
1516 parse2(cell->back(), FLAG_END, mode, false);
1519 else if (name == "math") {
1520 cell->push_back(MathAtom(new InsetMathEnsureMath(buf)));
1521 parse(cell->back().nucleus()->cell(0), FLAG_END, InsetMath::MATH_MODE);
1524 else if (name == "equation" || name == "equation*"
1525 || name == "displaymath") {
1526 if (mode != InsetMath::UNDECIDED_MODE) {
1527 error("bad math environment");
1530 cell->push_back(MathAtom(new InsetMathHull(buf, hullEquation)));
1531 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, (name == "equation"));
1534 else if (name == "eqnarray" || name == "eqnarray*") {
1535 if (mode != InsetMath::UNDECIDED_MODE) {
1536 error("bad math environment");
1539 cell->push_back(MathAtom(new InsetMathHull(buf, hullEqnArray)));
1540 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, !stared(name));
1543 else if (name == "align" || name == "align*") {
1544 if (mode != InsetMath::UNDECIDED_MODE) {
1545 error("bad math environment");
1548 cell->push_back(MathAtom(new InsetMathHull(buf, hullAlign)));
1549 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, !stared(name));
1552 else if (name == "flalign" || name == "flalign*") {
1553 if (mode != InsetMath::UNDECIDED_MODE) {
1554 error("bad math environment");
1557 cell->push_back(MathAtom(new InsetMathHull(buf, hullFlAlign)));
1558 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, !stared(name));
1561 else if (name == "alignat" || name == "alignat*") {
1562 if (mode != InsetMath::UNDECIDED_MODE) {
1563 error("bad math environment");
1566 // ignore this for a while
1568 cell->push_back(MathAtom(new InsetMathHull(buf, hullAlignAt)));
1569 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, !stared(name));
1572 else if (name == "xalignat" || name == "xalignat*") {
1573 if (mode != InsetMath::UNDECIDED_MODE) {
1574 error("bad math environment");
1577 // ignore this for a while
1579 cell->push_back(MathAtom(new InsetMathHull(buf, hullXAlignAt)));
1580 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, !stared(name));
1583 else if (name == "xxalignat") {
1584 if (mode != InsetMath::UNDECIDED_MODE) {
1585 error("bad math environment");
1588 // ignore this for a while
1590 cell->push_back(MathAtom(new InsetMathHull(buf, hullXXAlignAt)));
1591 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, !stared(name));
1594 else if (name == "multline" || name == "multline*") {
1595 if (mode != InsetMath::UNDECIDED_MODE) {
1596 error("bad math environment");
1599 cell->push_back(MathAtom(new InsetMathHull(buf, hullMultline)));
1600 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, !stared(name));
1603 else if (name == "gather" || name == "gather*") {
1604 if (mode != InsetMath::UNDECIDED_MODE) {
1605 error("bad math environment");
1608 cell->push_back(MathAtom(new InsetMathHull(buf, hullGather)));
1609 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, !stared(name));
1612 else if (latexkeys const * l = in_word_set(name)) {
1613 if (l->inset == "matrix") {
1614 cell->push_back(createInsetMath(name, buf));
1615 parse2(cell->back(), FLAG_END, mode, false);
1616 } else if (l->inset == "split") {
1617 docstring const valign = parse_verbatim_option() + 'c';
1618 cell->push_back(MathAtom(
1619 new InsetMathSplit(buf, name, (char)valign[0])));
1620 parse2(cell->back(), FLAG_END, mode, false);
1623 if (!(mode_ & Parse::QUIET)) {
1625 lyxerr << "found math environment `"
1627 << "' in symbols file with unsupported inset `"
1628 << to_utf8(l->inset)
1631 // create generic environment inset
1632 cell->push_back(MathAtom(new InsetMathEnv(buf, name)));
1633 parse(cell->back().nucleus()->cell(0), FLAG_END, mode);
1639 if (!(mode_ & Parse::QUIET)) {
1641 lyxerr << "found unknown math environment '"
1642 << to_utf8(name) << "'" << endl;
1644 // create generic environment inset
1645 cell->push_back(MathAtom(new InsetMathEnv(buf, name)));
1646 parse(cell->back().nucleus()->cell(0), FLAG_END, mode);
1650 else if (t.cs() == "kern") {
1655 Token const & t = getToken();
1659 while (num_tokens--)
1664 if (isValidLength(to_utf8(s)))
1668 cell->push_back(MathAtom(new InsetMathKern));
1670 cell->push_back(MathAtom(new InsetMathKern(s)));
1673 else if (t.cs() == "label") {
1674 // FIXME: This is swallowed in inline formulas
1675 docstring label = parse_verbatim_item();
1678 if (grid.asHullInset()) {
1679 grid.asHullInset()->label(cellrow, label);
1681 cell->push_back(createInsetMath(t.cs(), buf));
1682 cell->push_back(MathAtom(new InsetMathBrace(ar)));
1686 else if (t.cs() == "choose" || t.cs() == "over"
1687 || t.cs() == "atop" || t.cs() == "brace"
1688 || t.cs() == "brack") {
1689 MathAtom at = createInsetMath(t.cs(), buf);
1690 at.nucleus()->cell(0) = *cell;
1692 parse(at.nucleus()->cell(1), flags, mode);
1693 cell->push_back(at);
1697 else if (t.cs() == "color") {
1698 docstring const color = parse_verbatim_item();
1699 cell->push_back(MathAtom(new InsetMathColor(buf, true, color)));
1700 parse(cell->back().nucleus()->cell(0), flags, mode);
1704 else if (t.cs() == "textcolor") {
1705 docstring const color = parse_verbatim_item();
1706 cell->push_back(MathAtom(new InsetMathColor(buf, false, color)));
1707 parse(cell->back().nucleus()->cell(0), FLAG_ITEM, InsetMath::TEXT_MODE);
1710 else if (t.cs() == "normalcolor") {
1711 cell->push_back(createInsetMath(t.cs(), buf));
1712 parse(cell->back().nucleus()->cell(0), flags, mode);
1716 else if (t.cs() == "substack") {
1717 cell->push_back(createInsetMath(t.cs(), buf));
1718 parse2(cell->back(), FLAG_ITEM, mode, false);
1719 // Delete empty last row if present
1720 InsetMathGrid & subgrid =
1721 *(cell->back().nucleus()->asGridInset());
1722 if (subgrid.nrows() > 1)
1723 delEmptyLastRow(subgrid);
1726 else if (t.cs() == "xymatrix") {
1727 odocstringstream os;
1728 while (good() && nextToken().cat() != catBegin)
1729 os << getToken().asInput();
1730 cell->push_back(createInsetMath(t.cs() + os.str(), buf));
1731 parse2(cell->back(), FLAG_ITEM, mode, false);
1732 // Delete empty last row if present
1733 InsetMathGrid & subgrid =
1734 *(cell->back().nucleus()->asGridInset());
1735 if (subgrid.nrows() > 1)
1736 delEmptyLastRow(subgrid);
1739 else if (t.cs() == "Diagram") {
1740 odocstringstream os;
1741 while (good() && nextToken().cat() != catBegin)
1742 os << getToken().asInput();
1743 cell->push_back(createInsetMath(t.cs() + os.str(), buf));
1744 parse2(cell->back(), FLAG_ITEM, mode, false);
1747 else if (t.cs() == "framebox" || t.cs() == "makebox") {
1748 cell->push_back(createInsetMath(t.cs(), buf));
1749 parse(cell->back().nucleus()->cell(0), FLAG_OPTION, InsetMath::TEXT_MODE);
1750 parse(cell->back().nucleus()->cell(1), FLAG_OPTION, InsetMath::TEXT_MODE);
1751 parse(cell->back().nucleus()->cell(2), FLAG_ITEM, InsetMath::TEXT_MODE);
1754 else if (t.cs() == "tag") {
1755 if (nextToken().character() == '*') {
1757 cell->push_back(createInsetMath(t.cs() + '*', buf));
1759 cell->push_back(createInsetMath(t.cs(), buf));
1760 parse(cell->back().nucleus()->cell(0), FLAG_ITEM, InsetMath::TEXT_MODE);
1763 else if (t.cs() == "hspace") {
1764 bool const prot = nextToken().character() == '*';
1767 docstring const name = t.cs();
1768 docstring const arg = parse_verbatim_item();
1770 if (prot && arg == "\\fill")
1771 cell->push_back(MathAtom(new InsetMathSpace("hspace*{\\fill}", "")));
1772 else if (isValidLength(to_utf8(arg), &length))
1773 cell->push_back(MathAtom(new InsetMathSpace(length, prot)));
1775 // Since the Length class cannot use length variables
1776 // we must not create an InsetMathSpace.
1777 cell->push_back(MathAtom(new MathMacro(buf, name)));
1779 mathed_parse_cell(ar, '{' + arg + '}', mode_);
1785 else if (t.cs() == "infer") {
1787 parse(ar, FLAG_OPTION, mode);
1788 cell->push_back(createInsetMath(t.cs(), buf));
1789 parse2(cell->back(), FLAG_ITEM, mode, false);
1793 else if (1 && t.cs() == "ar") {
1794 auto_ptr<InsetMathXYArrow> p(new InsetMathXYArrow);
1795 // try to read target
1796 parse(p->cell(0), FLAG_OTPTION, mode);
1797 // try to read label
1798 if (nextToken().cat() == catSuper || nextToken().cat() == catSub) {
1799 p->up_ = nextToken().cat() == catSuper;
1801 parse(p->cell(1), FLAG_ITEM, mode);
1802 //lyxerr << "read label: " << p->cell(1) << endl;
1805 cell->push_back(MathAtom(p.release()));
1806 //lyxerr << "read cell: " << cell << endl;
1810 else if (t.cs() == "lyxmathsym") {
1812 if (getToken().cat() != catBegin) {
1813 error("'{' expected in \\" + t.cs());
1818 CatCode cat = nextToken().cat();
1819 while (good() && (count || cat != catEnd)) {
1820 if (cat == catBegin)
1822 else if (cat == catEnd)
1824 cmd += getToken().asInput();
1825 cat = nextToken().cat();
1827 if (getToken().cat() != catEnd) {
1828 error("'}' expected in \\" + t.cs());
1833 cmd = Encodings::fromLaTeXCommand(cmd,
1834 Encodings::MATH_CMD | Encodings::TEXT_CMD, rem);
1835 for (size_t i = 0; i < cmd.size(); ++i)
1836 cell->push_back(MathAtom(new InsetMathChar(cmd[i])));
1838 char_type c = rem[0];
1839 cell->push_back(MathAtom(new InsetMathChar(c)));
1840 cmd = rem.substr(1);
1844 } while (cmd.size());
1847 else if (t.cs().size()) {
1848 bool const no_mhchem =
1849 (t.cs() == "ce" || t.cs() == "cf")
1850 && buf && buf->params().use_package("mhchem") ==
1851 BufferParams::package_off;
1853 bool const is_user_macro = no_mhchem ||
1854 (buf && (mode_ & Parse::TRACKMACRO
1855 ? buf->usermacros.count(t.cs()) != 0
1856 : buf->getMacro(t.cs(), false) != 0));
1858 latexkeys const * l = in_word_set(t.cs());
1859 if (l && !is_user_macro) {
1860 if (l->inset == "big") {
1862 docstring const delim = getToken().asInput();
1863 if (InsetMathBig::isBigInsetDelim(delim))
1864 cell->push_back(MathAtom(
1865 new InsetMathBig(t.cs(), delim)));
1867 cell->push_back(createInsetMath(t.cs(), buf));
1872 else if (l->inset == "font") {
1873 cell->push_back(createInsetMath(t.cs(), buf));
1874 parse(cell->back().nucleus()->cell(0),
1875 FLAG_ITEM, asMode(mode, l->extra));
1878 else if (l->inset == "oldfont") {
1879 cell->push_back(createInsetMath(t.cs(), buf));
1880 parse(cell->back().nucleus()->cell(0),
1881 flags | FLAG_ALIGN, asMode(mode, l->extra));
1882 if (prevToken().cat() != catAlign &&
1883 prevToken().cs() != "\\")
1888 else if (l->inset == "style") {
1889 cell->push_back(createInsetMath(t.cs(), buf));
1890 parse(cell->back().nucleus()->cell(0),
1891 flags | FLAG_ALIGN, mode);
1892 if (prevToken().cat() != catAlign &&
1893 prevToken().cs() != "\\")
1899 MathAtom at = createInsetMath(t.cs(), buf);
1900 for (InsetMath::idx_type i = 0; i < at->nargs(); ++i)
1901 parse(at.nucleus()->cell(i),
1902 FLAG_ITEM, asMode(mode, l->extra));
1903 cell->push_back(at);
1908 bool is_unicode_symbol = false;
1909 if (mode == InsetMath::TEXT_MODE && !is_user_macro) {
1911 docstring cmd = prevToken().asInput();
1912 CatCode cat = nextToken().cat();
1913 if (cat == catBegin) {
1915 while (good() && (count || cat != catEnd)) {
1916 cat = nextToken().cat();
1917 cmd += getToken().asInput();
1919 if (cat == catBegin)
1921 else if (cat == catEnd)
1926 char_type c = Encodings::fromLaTeXCommand(cmd,
1927 Encodings::MATH_CMD | Encodings::TEXT_CMD,
1930 if (cat == catLetter)
1932 cmd += getToken().asInput();
1934 if (cat == catLetter)
1936 c = Encodings::fromLaTeXCommand(cmd,
1937 Encodings::MATH_CMD | Encodings::TEXT_CMD,
1941 is_unicode_symbol = true;
1942 cell->push_back(MathAtom(new InsetMathChar(c)));
1944 while (num_tokens--)
1948 if (!is_unicode_symbol) {
1949 MathAtom at = is_user_macro ?
1950 MathAtom(new MathMacro(buf, t.cs()))
1951 : createInsetMath(t.cs(), buf);
1952 InsetMath::mode_type m = mode;
1953 //if (m == InsetMath::UNDECIDED_MODE)
1954 //lyxerr << "default creation: m1: " << m << endl;
1955 if (at->currentMode() != InsetMath::UNDECIDED_MODE)
1956 m = at->currentMode();
1957 //lyxerr << "default creation: m2: " << m << endl;
1958 InsetMath::idx_type start = 0;
1959 // this fails on \bigg[...\bigg]
1961 //parse(opt, FLAG_OPTION, InsetMath::VERBATIM_MODE);
1964 // at.nucleus()->cell(0) = opt;
1966 for (InsetMath::idx_type i = start; i < at->nargs(); ++i) {
1967 parse(at.nucleus()->cell(i), FLAG_ITEM, m);
1970 cell->push_back(at);
1976 if (flags & FLAG_LEAVE) {
1977 flags &= ~FLAG_LEAVE;
1986 } // anonymous namespace
1989 bool mathed_parse_cell(MathData & ar, docstring const & str, Parse::flags f)
1991 return Parser(str, f, ar.buffer()).parse(ar, 0, f & Parse::TEXTMODE ?
1992 InsetMath::TEXT_MODE : InsetMath::MATH_MODE);
1996 bool mathed_parse_cell(MathData & ar, istream & is, Parse::flags f)
1998 return Parser(is, f, ar.buffer()).parse(ar, 0, f & Parse::TEXTMODE ?
1999 InsetMath::TEXT_MODE : InsetMath::MATH_MODE);
2003 bool mathed_parse_normal(Buffer * buf, MathAtom & t, docstring const & str,
2006 return Parser(str, f, buf).parse(t);
2010 bool mathed_parse_normal(Buffer * buf, MathAtom & t, Lexer & lex,
2013 return Parser(lex, f, buf).parse(t);
2017 bool mathed_parse_normal(InsetMathGrid & grid, docstring const & str,
2020 return Parser(str, f, &grid.buffer()).parse1(grid, 0, f & Parse::TEXTMODE ?
2021 InsetMath::TEXT_MODE : InsetMath::MATH_MODE, false);
2027 fill(theCatcode, theCatcode + 128, catOther);
2028 fill(theCatcode + 'a', theCatcode + 'z' + 1, catLetter);
2029 fill(theCatcode + 'A', theCatcode + 'Z' + 1, catLetter);
2031 theCatcode[int('\\')] = catEscape;
2032 theCatcode[int('{')] = catBegin;
2033 theCatcode[int('}')] = catEnd;
2034 theCatcode[int('$')] = catMath;
2035 theCatcode[int('&')] = catAlign;
2036 theCatcode[int('\n')] = catNewline;
2037 theCatcode[int('#')] = catParameter;
2038 theCatcode[int('^')] = catSuper;
2039 theCatcode[int('_')] = catSub;
2040 theCatcode[int(0x7f)] = catIgnore;
2041 theCatcode[int(' ')] = catSpace;
2042 theCatcode[int('\t')] = catSpace;
2043 theCatcode[int('\r')] = catNewline;
2044 theCatcode[int('~')] = catActive;
2045 theCatcode[int('%')] = catComment;