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 "InsetMathChar.h"
46 #include "InsetMathColor.h"
47 #include "InsetMathComment.h"
48 #include "InsetMathDelim.h"
49 #include "InsetMathEnv.h"
50 #include "InsetMathFrac.h"
51 #include "InsetMathKern.h"
52 #include "MathMacro.h"
53 #include "InsetMathPar.h"
54 #include "InsetMathRef.h"
55 #include "InsetMathRoot.h"
56 #include "InsetMathScript.h"
57 #include "InsetMathSpace.h"
58 #include "InsetMathSplit.h"
59 #include "InsetMathSqrt.h"
60 #include "InsetMathTabular.h"
61 #include "MathMacroTemplate.h"
62 #include "MathFactory.h"
63 #include "MathMacroArgument.h"
64 #include "MathSupport.h"
69 #include "support/debug.h"
70 #include "support/convert.h"
71 #include "support/docstream.h"
72 #include "support/lstrings.h"
86 InsetMath::mode_type asMode(InsetMath::mode_type oldmode, docstring const & str)
88 //lyxerr << "handling mode: '" << str << "'" << endl;
89 if (str == "mathmode")
90 return InsetMath::MATH_MODE;
91 if (str == "textmode" || str == "forcetext")
92 return InsetMath::TEXT_MODE;
97 bool stared(docstring const & s)
99 size_t const n = s.size();
100 return n && s[n - 1] == '*';
104 docstring escapeSpecialChars(docstring const & str, bool textmode)
106 docstring const backslash = textmode ? from_ascii("\\textbackslash ")
107 : from_ascii("\\backslash ");
108 docstring const caret = textmode ? from_ascii("\\textasciicircum ")
109 : from_ascii("\\mathcircumflex ");
111 return subst(subst(subst(subst(subst(subst(subst(subst(subst(str,
112 from_ascii("\\"), backslash),
113 from_ascii("^"), caret),
114 from_ascii("_"), from_ascii("\\_")),
115 from_ascii("$"), from_ascii("\\$")),
116 from_ascii("#"), from_ascii("\\#")),
117 from_ascii("&"), from_ascii("\\&")),
118 from_ascii("%"), from_ascii("\\%")),
119 from_ascii("{"), from_ascii("\\{")),
120 from_ascii("}"), from_ascii("\\}"));
125 * Add the row \p cellrow to \p grid.
126 * \returns wether the row could be added. Adding a row can fail for
127 * environments like "equation" that have a fixed number of rows.
129 bool addRow(InsetMathGrid & grid, InsetMathGrid::row_type & cellrow,
130 docstring const & vskip, bool allow_newpage_ = true)
133 if (cellrow == grid.nrows()) {
134 //lyxerr << "adding row " << cellrow << endl;
135 grid.addRow(cellrow - 1);
136 if (cellrow == grid.nrows()) {
137 // We can't add a row to this grid, so let's
138 // append the content of this cell to the previous
140 // This does not happen in well formed .lyx files,
141 // but LyX versions 1.3.x and older could create
142 // such files and tex2lyx can still do that.
144 lyxerr << "ignoring extra row";
146 lyxerr << " with extra space " << to_utf8(vskip);
148 lyxerr << " with no page break allowed";
149 lyxerr << '.' << endl;
153 grid.vcrskip(Length(to_utf8(vskip)), cellrow - 1);
154 grid.rowinfo(cellrow - 1).allow_newpage_ = allow_newpage_;
160 * Add the column \p cellcol to \p grid.
161 * \returns wether the column could be added. Adding a column can fail for
162 * environments like "eqnarray" that have a fixed number of columns.
164 bool addCol(InsetMathGrid & grid, InsetMathGrid::col_type & cellcol)
167 if (cellcol == grid.ncols()) {
168 //lyxerr << "adding column " << cellcol << endl;
169 grid.addCol(cellcol);
170 if (cellcol == grid.ncols()) {
171 // We can't add a column to this grid, so let's
172 // append the content of this cell to the previous
174 // This does not happen in well formed .lyx files,
175 // but LyX versions 1.3.x and older could create
176 // such files and tex2lyx can still do that.
178 lyxerr << "ignoring extra column." << endl;
187 * Check wether the last row is empty and remove it if yes.
188 * Otherwise the following code
196 * will result in a grid with 3 rows (+ the dummy row that is always present),
197 * because the last '\\' opens a new row.
199 void delEmptyLastRow(InsetMathGrid & grid)
201 InsetMathGrid::row_type const row = grid.nrows() - 1;
202 for (InsetMathGrid::col_type col = 0; col < grid.ncols(); ++col) {
203 if (!grid.cell(grid.index(row, col)).empty())
206 // Copy the row information of the empty row (which would contain the
207 // last hline in the example above) to the dummy row and delete the
209 grid.rowinfo(row + 1) = grid.rowinfo(row);
214 // These are TeX's catcodes
216 catEscape, // 0 backslash
226 catSpace, // 10 space
227 catLetter, // 11 a-zA-Z
228 catOther, // 12 none of the above
231 catInvalid // 15 <delete>
234 CatCode theCatcode[128];
237 inline CatCode catcode(char_type c)
239 /* The only characters that are not catOther lie in the pure ASCII
240 * range. Therefore theCatcode has only 128 entries.
241 * TeX itself deals with 8bit characters, so if needed this table
242 * could be enlarged to 256 entries.
243 * Any larger value does not make sense, since the fact that we use
244 * unicode internally does not change Knuth's TeX engine.
245 * Apart from that a table for the full 21bit UCS4 range would waste
246 * too much memory. */
250 return theCatcode[c];
255 FLAG_ALIGN = 1 << 0, // next & or \\ ends the parsing process
256 FLAG_BRACE_LAST = 1 << 1, // next closing brace ends the parsing
257 FLAG_RIGHT = 1 << 2, // next \\right ends the parsing process
258 FLAG_END = 1 << 3, // next \\end ends the parsing process
259 FLAG_BRACK_LAST = 1 << 4, // next closing bracket ends the parsing
260 FLAG_TEXTMODE = 1 << 5, // we are in a box
261 FLAG_ITEM = 1 << 6, // read a (possibly braced) token
262 FLAG_LEAVE = 1 << 7, // leave the loop at the end
263 FLAG_SIMPLE = 1 << 8, // next $ leaves the loop
264 FLAG_EQUATION = 1 << 9, // next \] leaves the loop
265 FLAG_SIMPLE2 = 1 << 10, // next \) leaves the loop
266 FLAG_OPTION = 1 << 11, // read [...] style option
267 FLAG_BRACED = 1 << 12 // read {...} style argument
272 // Helper class for parsing
278 Token() : cs_(), char_(0), cat_(catIgnore) {}
280 Token(char_type c, CatCode cat) : cs_(), char_(c), cat_(cat) {}
282 explicit Token(docstring const & cs) : cs_(cs), char_(0), cat_(catIgnore) {}
285 docstring const & cs() const { return cs_; }
287 CatCode cat() const { return cat_; }
289 char_type character() const { return char_; }
291 docstring asString() const { return cs_.size() ? cs_ : docstring(1, char_); }
293 docstring asInput() const { return cs_.size() ? '\\' + cs_ : docstring(1, char_); }
305 ostream & operator<<(ostream & os, Token const & t)
308 docstring const & cs = t.cs();
309 // FIXME: For some strange reason, the stream operator instanciate
310 // a new Token before outputting the contents of t.cs().
311 // Because of this the line
313 // below becomes recursive.
314 // In order to avoid that we return early:
317 os << '\\' << to_utf8(cs);
319 else if (t.cat() == catLetter)
322 os << '[' << t.character() << ',' << t.cat() << ']';
330 typedef InsetMath::mode_type mode_type;
332 typedef Parse::flags parse_mode;
335 Parser(Lexer & lex, parse_mode mode);
336 /// Only use this for reading from .lyx file format, for the reason
337 /// see Parser::tokenize(istream &).
338 Parser(istream & is, parse_mode mode);
340 Parser(docstring const & str, parse_mode mode);
343 bool parse(MathAtom & at);
345 bool parse(MathData & array, unsigned flags, mode_type mode);
347 bool parse1(InsetMathGrid & grid, unsigned flags, mode_type mode,
350 MathData parse(unsigned flags, mode_type mode);
352 int lineno() const { return lineno_; }
358 void parse2(MathAtom & at, unsigned flags, mode_type mode, bool numbered);
359 /// get arg delimited by 'left' and 'right'
360 docstring getArg(char_type left, char_type right);
364 void error(string const & msg);
365 void error(docstring const & msg) { error(to_utf8(msg)); }
366 /// dump contents to screen
368 /// Only use this for reading from .lyx file format (see
369 /// implementation for reason)
370 void tokenize(istream & is);
372 void tokenize(docstring const & s);
374 void skipSpaceTokens(idocstream & is, char_type c);
376 void push_back(Token const & t);
380 Token const & prevToken() const;
382 Token const & nextToken() const;
384 Token const & getToken();
385 /// skips spaces if any
388 void lex(docstring const & s);
392 docstring parse_verbatim_item();
394 docstring parse_verbatim_option();
399 vector<Token> tokens_;
402 /// Stack of active environments
403 vector<docstring> environments_;
411 Parser::Parser(Lexer & lexer, parse_mode mode)
412 : lineno_(lexer.lineNumber()), pos_(0), mode_(mode), success_(true)
414 tokenize(lexer.getStream());
419 Parser::Parser(istream & is, parse_mode mode)
420 : lineno_(0), pos_(0), mode_(mode), success_(true)
426 Parser::Parser(docstring const & str, parse_mode mode)
427 : lineno_(0), pos_(0), mode_(mode), success_(true)
433 void Parser::push_back(Token const & t)
435 tokens_.push_back(t);
439 void Parser::pop_back()
445 Token const & Parser::prevToken() const
447 static const Token dummy;
448 return pos_ > 0 ? tokens_[pos_ - 1] : dummy;
452 Token const & Parser::nextToken() const
454 static const Token dummy;
455 return good() ? tokens_[pos_] : dummy;
459 Token const & Parser::getToken()
461 static const Token dummy;
462 //lyxerr << "looking at token " << tokens_[pos_] << " pos: " << pos_ << endl;
463 return good() ? tokens_[pos_++] : dummy;
467 void Parser::skipSpaces()
469 while (nextToken().cat() == catSpace || nextToken().cat() == catNewline)
474 void Parser::putback()
480 bool Parser::good() const
482 return pos_ < tokens_.size();
486 char_type Parser::getChar()
489 error("The input stream is not well...");
493 return tokens_[pos_++].character();
497 docstring Parser::getArg(char_type left, char_type right)
502 char_type c = getChar();
507 while ((c = getChar()) != right && good())
514 void Parser::skipSpaceTokens(idocstream & is, char_type c)
516 // skip trailing spaces
517 while (catcode(c) == catSpace || catcode(c) == catNewline)
520 //lyxerr << "putting back: " << c << endl;
525 void Parser::tokenize(istream & is)
527 // eat everything up to the next \end_inset or end of stream
528 // and store it in s for further tokenization
533 if (s.size() >= 10 && s.substr(s.size() - 10) == "\\end_inset") {
534 s = s.substr(0, s.size() - 10);
538 // Remove the space after \end_inset
539 if (is.get(c) && c != ' ')
543 tokenize(from_utf8(s));
547 void Parser::tokenize(docstring const & buffer)
549 idocstringstream is(mode_ & Parse::VERBATIM
550 ? escapeSpecialChars(buffer, mode_ & Parse::TEXTMODE)
551 : buffer, ios::in | ios::binary);
555 //lyxerr << "reading c: " << c << endl;
557 switch (catcode(c)) {
561 if (catcode(c) == catNewline)
562 ; //push_back(Token("par"));
564 push_back(Token('\n', catNewline));
572 while (is.get(c) && catcode(c) != catNewline)
582 error("unexpected end of input");
585 if (catcode(c) == catLetter) {
587 while (is.get(c) && catcode(c) == catLetter)
589 skipSpaceTokens(is, c);
598 push_back(Token(c, catcode(c)));
600 skipSpaceTokens(is, c);
605 if (!(mode_ & Parse::QUIET))
606 lyxerr << "ignoring a char: " << int(c) << endl;
611 push_back(Token(c, catcode(c)));
621 void Parser::dump() const
623 lyxerr << "\nTokens: ";
624 for (unsigned i = 0; i < tokens_.size(); ++i) {
627 lyxerr << tokens_[i];
629 lyxerr << " pos: " << pos_ << endl;
633 void Parser::error(string const & msg)
636 if (!(mode_ & Parse::QUIET)) {
637 lyxerr << "Line ~" << lineno_ << ": Math parse error: "
644 bool Parser::parse(MathAtom & at)
648 parse(ar, false, InsetMath::UNDECIDED_MODE);
649 if (ar.size() != 1 || ar.front()->getType() == hullNone) {
650 if (!(mode_ & Parse::QUIET))
651 lyxerr << "unusual contents found: " << ar << endl;
652 at = MathAtom(new InsetMathPar(ar));
653 //if (at->nargs() > 0)
654 // at.nucleus()->cell(0) = ar;
656 // lyxerr << "unusual contents found: " << ar << endl;
664 docstring Parser::parse_verbatim_option()
668 if (nextToken().character() == '[') {
669 Token t = getToken();
670 for (Token t = getToken(); t.character() != ']' && good(); t = getToken()) {
671 if (t.cat() == catBegin) {
673 res += '{' + parse_verbatim_item() + '}';
682 docstring Parser::parse_verbatim_item()
686 if (nextToken().cat() == catBegin) {
687 Token t = getToken();
688 for (Token t = getToken(); t.cat() != catEnd && good(); t = getToken()) {
689 if (t.cat() == catBegin) {
691 res += '{' + parse_verbatim_item() + '}';
701 MathData Parser::parse(unsigned flags, mode_type mode)
704 parse(ar, flags, mode);
709 bool Parser::parse(MathData & array, unsigned flags, mode_type mode)
711 InsetMathGrid grid(1, 1);
712 parse1(grid, flags, mode, false);
713 array = grid.cell(0);
718 void Parser::parse2(MathAtom & at, const unsigned flags, const mode_type mode,
721 parse1(*(at.nucleus()->asGridInset()), flags, mode, numbered);
725 bool Parser::parse1(InsetMathGrid & grid, unsigned flags,
726 const mode_type mode, const bool numbered)
729 InsetMathGrid::row_type cellrow = 0;
730 InsetMathGrid::col_type cellcol = 0;
731 MathData * cell = &grid.cell(grid.index(cellrow, cellcol));
733 if (grid.asHullInset())
734 grid.asHullInset()->numbered(cellrow, numbered);
737 //lyxerr << " flags: " << flags << endl;
738 //lyxerr << " mode: " << mode << endl;
739 //lyxerr << "grid: " << grid << endl;
742 Token const & t = getToken();
745 lyxerr << "t: " << t << " flags: " << flags << endl;
746 lyxerr << "mode: " << mode << endl;
751 if (flags & FLAG_ITEM) {
753 if (t.cat() == catBegin) {
754 // skip the brace and collect everything to the next matching
756 parse1(grid, FLAG_BRACE_LAST, mode, numbered);
760 // handle only this single token, leave the loop if done
765 if (flags & FLAG_BRACED) {
766 if (t.cat() == catSpace)
769 if (t.cat() != catBegin) {
770 error("opening brace expected");
774 // skip the brace and collect everything to the next matching
776 flags = FLAG_BRACE_LAST;
780 if (flags & FLAG_OPTION) {
781 if (t.cat() == catOther && t.character() == '[') {
783 parse(ar, FLAG_BRACK_LAST, mode);
786 // no option found, put back token and we are done
795 if (t.cat() == catMath) {
796 if (mode != InsetMath::MATH_MODE) {
797 // we are inside some text mode thingy, so opening new math is allowed
798 Token const & n = getToken();
799 if (n.cat() == catMath) {
800 // TeX's $$...$$ syntax for displayed math
801 cell->push_back(MathAtom(new InsetMathHull(hullEquation)));
802 parse2(cell->back(), FLAG_SIMPLE, InsetMath::MATH_MODE, false);
803 getToken(); // skip the second '$' token
805 // simple $...$ stuff
807 cell->push_back(MathAtom(new InsetMathHull(hullSimple)));
808 parse2(cell->back(), FLAG_SIMPLE, InsetMath::MATH_MODE, false);
812 else if (flags & FLAG_SIMPLE) {
813 // this is the end of the formula
818 error("something strange in the parser");
823 else if (t.cat() == catLetter)
824 cell->push_back(MathAtom(new InsetMathChar(t.character())));
826 else if (t.cat() == catSpace && mode != InsetMath::MATH_MODE) {
827 if (cell->empty() || cell->back()->getChar() != ' ')
828 cell->push_back(MathAtom(new InsetMathChar(t.character())));
831 else if (t.cat() == catNewline && mode != InsetMath::MATH_MODE) {
832 if (cell->empty() || cell->back()->getChar() != ' ')
833 cell->push_back(MathAtom(new InsetMathChar(' ')));
836 else if (t.cat() == catParameter) {
837 Token const & n = getToken();
838 cell->push_back(MathAtom(new MathMacroArgument(n.character()-'0')));
841 else if (t.cat() == catActive)
842 cell->push_back(MathAtom(new InsetMathChar(t.character())));
844 else if (t.cat() == catBegin) {
846 parse(ar, FLAG_BRACE_LAST, mode);
847 // do not create a BraceInset if they were written by LyX
848 // this helps to keep the annoyance of "a choose b" to a minimum
849 if (ar.size() == 1 && ar[0]->extraBraces())
852 cell->push_back(MathAtom(new InsetMathBrace(ar)));
855 else if (t.cat() == catEnd) {
856 if (flags & FLAG_BRACE_LAST)
858 error("found '}' unexpectedly");
859 //LASSERT(false, /**/);
860 //add(cell, '}', LM_TC_TEX);
863 else if (t.cat() == catAlign) {
864 //lyxerr << " column now " << (cellcol + 1)
865 // << " max: " << grid.ncols() << endl;
866 if (flags & FLAG_ALIGN)
868 if (addCol(grid, cellcol))
869 cell = &grid.cell(grid.index(cellrow, cellcol));
872 else if (t.cat() == catSuper || t.cat() == catSub) {
873 bool up = (t.cat() == catSuper);
874 // we need no new script inset if the last thing was a scriptinset,
875 // which has that script already not the same script already
877 cell->push_back(MathAtom(new InsetMathScript(up)));
878 else if (cell->back()->asScriptInset() &&
879 !cell->back()->asScriptInset()->has(up))
880 cell->back().nucleus()->asScriptInset()->ensure(up);
881 else if (cell->back()->asScriptInset())
882 cell->push_back(MathAtom(new InsetMathScript(up)));
884 cell->back() = MathAtom(new InsetMathScript(cell->back(), up));
885 InsetMathScript * p = cell->back().nucleus()->asScriptInset();
886 // special handling of {}-bases
887 // Here we could remove the brace inset for things
888 // like {a'}^2 and add the braces back in
889 // InsetMathScript::write().
890 // We do not do it, since it is not possible to detect
891 // reliably whether the braces are needed because the
892 // nucleus contains more than one symbol, or whether
893 // they are needed for unknown commands like \xx{a}_0
894 // or \yy{a}{b}_0. This was done in revision 14819
895 // in an unreliable way. See this thread
896 // http://www.mail-archive.com/lyx-devel%40lists.lyx.org/msg104917.html
898 parse(p->cell(p->idxOfScript(up)), FLAG_ITEM, mode);
905 else if (t.character() == ']' && (flags & FLAG_BRACK_LAST)) {
906 //lyxerr << "finished reading option" << endl;
910 else if (t.cat() == catOther) {
911 char_type c = t.character();
912 if (isAsciiOrMathAlpha(c)
913 || mode_ & Parse::VERBATIM
914 || !(mode_ & Parse::USETEXT)
915 || mode == InsetMath::TEXT_MODE) {
916 cell->push_back(MathAtom(new InsetMathChar(c)));
918 MathAtom at = createInsetMath("text");
919 at.nucleus()->cell(0).push_back(MathAtom(new InsetMathChar(c)));
920 while (nextToken().cat() == catOther
921 && !isAsciiOrMathAlpha(nextToken().character())) {
922 c = getToken().character();
923 at.nucleus()->cell(0).push_back(MathAtom(new InsetMathChar(c)));
929 else if (t.cat() == catComment) {
932 Token const & t = getToken();
933 if (t.cat() == catNewline)
937 cell->push_back(MathAtom(new InsetMathComment(s)));
945 else if (t.cs() == "lyxlock") {
947 cell->back().nucleus()->lock(true);
950 else if ((t.cs() == "global" && nextToken().cs() == "def") ||
952 if (t.cs() == "global")
956 docstring name = getToken().cs();
961 while (good() && nextToken().cat() != catBegin) {
962 pars += getToken().cs();
969 parse(def, FLAG_ITEM, InsetMath::UNDECIDED_MODE);
971 // is a version for display attached?
974 if (nextToken().cat() == catBegin)
975 parse(display, FLAG_ITEM, InsetMath::MATH_MODE);
977 cell->push_back(MathAtom(new MathMacroTemplate(name, nargs,
978 0, MacroTypeDef, vector<MathData>(), def, display)));
981 else if (t.cs() == "newcommand" ||
982 t.cs() == "renewcommand" ||
983 t.cs() == "newlyxcommand") {
985 if (getToken().cat() != catBegin) {
986 error("'{' in \\newcommand expected (1) ");
989 docstring name = getToken().cs();
990 if (getToken().cat() != catEnd) {
991 error("'}' in \\newcommand expected");
996 docstring const arg = getArg('[', ']');
999 nargs = convert<int>(arg);
1001 // optional argument given?
1004 vector<MathData> optionalValues;
1005 while (nextToken().character() == '[') {
1007 optionalValues.push_back(MathData());
1008 parse(optionalValues[optionals], FLAG_BRACK_LAST, mode);
1013 parse(def, FLAG_ITEM, InsetMath::UNDECIDED_MODE);
1015 // is a version for display attached?
1018 if (nextToken().cat() == catBegin)
1019 parse(display, FLAG_ITEM, InsetMath::MATH_MODE);
1021 cell->push_back(MathAtom(new MathMacroTemplate(name, nargs,
1022 optionals, MacroTypeNewcommand, optionalValues, def, display)));
1026 else if (t.cs() == "newcommandx" ||
1027 t.cs() == "renewcommandx") {
1028 // \newcommandx{\foo}[2][usedefault, addprefix=\global,1=default]{#1,#2}
1031 if (nextToken().cat() == catBegin) {
1033 name = getToken().cs();
1034 if (getToken().cat() != catEnd) {
1035 error("'}' in \\newcommandx expected");
1039 name = getToken().cs();
1042 docstring const arg = getArg('[', ']');
1044 error("[num] in \\newcommandx expected");
1047 int nargs = convert<int>(arg);
1051 vector<MathData> optionalValues;
1052 if (nextToken().character() == '[') {
1056 // handle 'opt=value' options, separated by ','.
1058 while (nextToken().character() != ']' && good()) {
1059 if (nextToken().character() >= '1'
1060 && nextToken().character() <= '9') {
1061 // optional value -> get parameter number
1062 int n = getChar() - '0';
1064 error("Arity of \\newcommandx too low "
1065 "for given optional parameter.");
1070 if (getToken().character() != '=') {
1071 error("'=' and optional parameter value "
1072 "expected for \\newcommandx");
1077 int optNum = max(size_t(n), optionalValues.size());
1078 optionalValues.resize(optNum);
1079 optionalValues[n - 1].clear();
1080 while (nextToken().character() != ']'
1081 && nextToken().character() != ',') {
1083 parse(data, FLAG_ITEM, InsetMath::UNDECIDED_MODE);
1084 optionalValues[n - 1].append(data);
1086 optionals = max(n, optionals);
1087 } else if (nextToken().cat() == catLetter) {
1088 // we in fact ignore every non-optional
1093 while (nextToken().cat() == catLetter)
1099 if (nextToken().character() == '=') {
1101 while (nextToken().character() != ']'
1102 && nextToken().character() != ',')
1103 parse(value, FLAG_ITEM,
1104 InsetMath::UNDECIDED_MODE);
1107 error("option for \\newcommandx expected");
1113 if (nextToken().character() == ',') {
1116 } else if (nextToken().character() != ']') {
1117 error("Expecting ',' or ']' in options "
1118 "of \\newcommandx");
1131 parse(def, FLAG_ITEM, InsetMath::UNDECIDED_MODE);
1133 // is a version for display attached?
1136 if (nextToken().cat() == catBegin)
1137 parse(display, FLAG_ITEM, InsetMath::MATH_MODE);
1139 cell->push_back(MathAtom(new MathMacroTemplate(name, nargs,
1140 optionals, MacroTypeNewcommandx, optionalValues, def,
1144 else if (t.cs() == "(") {
1145 if (mode == InsetMath::MATH_MODE) {
1146 error("bad math environment");
1149 cell->push_back(MathAtom(new InsetMathHull(hullSimple)));
1150 parse2(cell->back(), FLAG_SIMPLE2, InsetMath::MATH_MODE, false);
1153 else if (t.cs() == "[") {
1154 if (mode != InsetMath::UNDECIDED_MODE) {
1155 error("bad math environment");
1158 cell->push_back(MathAtom(new InsetMathHull(hullEquation)));
1159 parse2(cell->back(), FLAG_EQUATION, InsetMath::MATH_MODE, false);
1162 else if (t.cs() == "protect")
1163 // ignore \\protect, will hopefully be re-added during output
1166 else if (t.cs() == "end") {
1167 if (flags & FLAG_END) {
1168 // eat environment name
1169 docstring const name = getArg('{', '}');
1170 if (environments_.empty())
1171 error("'found \\end{" + name +
1172 "}' without matching '\\begin{" +
1174 else if (name != environments_.back())
1175 error("'\\end{" + name +
1176 "}' does not match '\\begin{" +
1177 environments_.back() + "}'");
1179 environments_.pop_back();
1180 // Delete empty last row in matrix
1182 // If you abuse InsetMathGrid for
1183 // non-matrix like structures you
1184 // probably need to refine this test.
1185 // Right now we only have to test for
1186 // single line hull insets.
1187 if (grid.nrows() > 1)
1188 delEmptyLastRow(grid);
1192 error("found 'end' unexpectedly");
1195 else if (t.cs() == ")") {
1196 if (flags & FLAG_SIMPLE2)
1198 error("found '\\)' unexpectedly");
1201 else if (t.cs() == "]") {
1202 if (flags & FLAG_EQUATION)
1204 error("found '\\]' unexpectedly");
1207 else if (t.cs() == "\\") {
1208 if (flags & FLAG_ALIGN)
1211 if (nextToken().asInput() == "*") {
1213 added = addRow(grid, cellrow, docstring(), false);
1215 added = addRow(grid, cellrow, getArg('[', ']'));
1217 error("missing token after \\\\");
1220 if (grid.asHullInset())
1221 grid.asHullInset()->numbered(
1223 cell = &grid.cell(grid.index(cellrow,
1229 else if (t.cs() == "multicolumn") {
1230 // extract column count and insert dummy cells
1232 parse(count, FLAG_ITEM, mode);
1234 if (!extractNumber(count, cols)) {
1236 lyxerr << " can't extract number of cells from " << count << endl;
1238 // resize the table if necessary
1239 for (int i = 0; i < cols; ++i) {
1240 if (addCol(grid, cellcol)) {
1241 cell = &grid.cell(grid.index(
1243 // mark this as dummy
1244 grid.cellinfo(grid.index(
1245 cellrow, cellcol)).dummy_ = true;
1248 // the last cell is the real thing, not a dummy
1249 grid.cellinfo(grid.index(cellrow, cellcol)).dummy_ = false;
1251 // read special alignment
1253 parse(align, FLAG_ITEM, mode);
1254 //grid.cellinfo(grid.index(cellrow, cellcol)).align_ = extractString(align);
1256 // parse the remaining contents into the "real" cell
1257 parse(*cell, FLAG_ITEM, mode);
1261 else if (t.cs() == "limits")
1264 else if (t.cs() == "nolimits")
1267 else if (t.cs() == "nonumber") {
1268 if (grid.asHullInset())
1269 grid.asHullInset()->numbered(cellrow, false);
1272 else if (t.cs() == "number") {
1273 if (grid.asHullInset())
1274 grid.asHullInset()->numbered(cellrow, true);
1277 else if (t.cs() == "hline") {
1278 grid.rowinfo(cellrow).lines_ ++;
1281 else if (t.cs() == "sqrt") {
1283 parse(ar, FLAG_OPTION, mode);
1285 cell->push_back(MathAtom(new InsetMathRoot));
1286 cell->back().nucleus()->cell(0) = ar;
1287 parse(cell->back().nucleus()->cell(1), FLAG_ITEM, mode);
1289 cell->push_back(MathAtom(new InsetMathSqrt));
1290 parse(cell->back().nucleus()->cell(0), FLAG_ITEM, mode);
1294 else if (t.cs() == "unit") {
1295 // Allowed formats \unit[val]{unit}
1297 parse(ar, FLAG_OPTION, mode);
1299 cell->push_back(MathAtom(new InsetMathFrac(InsetMathFrac::UNIT)));
1300 cell->back().nucleus()->cell(0) = ar;
1301 parse(cell->back().nucleus()->cell(1), FLAG_ITEM, mode);
1303 cell->push_back(MathAtom(new InsetMathFrac(InsetMathFrac::UNIT, 1)));
1304 parse(cell->back().nucleus()->cell(0), FLAG_ITEM, mode);
1308 else if (t.cs() == "unitfrac") {
1309 // Here allowed formats are \unitfrac[val]{num}{denom}
1311 parse(ar, FLAG_OPTION, mode);
1313 cell->push_back(MathAtom(new InsetMathFrac(InsetMathFrac::UNITFRAC, 3)));
1314 cell->back().nucleus()->cell(2) = ar;
1316 cell->push_back(MathAtom(new InsetMathFrac(InsetMathFrac::UNITFRAC)));
1318 parse(cell->back().nucleus()->cell(0), FLAG_ITEM, mode);
1319 parse(cell->back().nucleus()->cell(1), FLAG_ITEM, mode);
1322 else if (t.cs() == "cfrac") {
1323 // Here allowed formats are \cfrac[pos]{num}{denom}
1325 parse(ar, FLAG_OPTION, mode);
1327 cell->push_back(MathAtom(new InsetMathFrac(InsetMathFrac::CFRAC, 3)));
1328 cell->back().nucleus()->cell(2) = ar;
1330 cell->push_back(MathAtom(new InsetMathFrac(InsetMathFrac::CFRAC)));
1332 parse(cell->back().nucleus()->cell(0), FLAG_ITEM, mode);
1333 parse(cell->back().nucleus()->cell(1), FLAG_ITEM, mode);
1336 else if (t.cs() == "xrightarrow" || t.cs() == "xleftarrow") {
1337 cell->push_back(createInsetMath(t.cs()));
1338 parse(cell->back().nucleus()->cell(1), FLAG_OPTION, mode);
1339 parse(cell->back().nucleus()->cell(0), FLAG_ITEM, mode);
1342 else if (t.cs() == "ref" || t.cs() == "eqref" || t.cs() == "prettyref"
1343 || t.cs() == "pageref" || t.cs() == "vpageref" || t.cs() == "vref") {
1344 cell->push_back(MathAtom(new InsetMathRef(t.cs())));
1345 parse(cell->back().nucleus()->cell(1), FLAG_OPTION, mode);
1346 parse(cell->back().nucleus()->cell(0), FLAG_ITEM, mode);
1349 else if (t.cs() == "left") {
1351 Token const & tl = getToken();
1352 // \| and \Vert are equivalent, and InsetMathDelim
1354 // FIXME: fix this in InsetMathDelim itself!
1355 docstring const l = tl.cs() == "|" ? from_ascii("Vert") : tl.asString();
1357 parse(ar, FLAG_RIGHT, mode);
1361 Token const & tr = getToken();
1362 docstring const r = tr.cs() == "|" ? from_ascii("Vert") : tr.asString();
1363 cell->push_back(MathAtom(new InsetMathDelim(l, r, ar)));
1366 else if (t.cs() == "right") {
1367 if (flags & FLAG_RIGHT)
1369 //lyxerr << "got so far: '" << cell << "'" << endl;
1370 error("Unmatched right delimiter");
1374 else if (t.cs() == "begin") {
1375 docstring const name = getArg('{', '}');
1376 environments_.push_back(name);
1378 if (name == "array" || name == "subarray") {
1379 docstring const valign = parse_verbatim_option() + 'c';
1380 docstring const halign = parse_verbatim_item();
1381 cell->push_back(MathAtom(new InsetMathArray(name,
1382 InsetMathGrid::guessColumns(halign), 1, (char)valign[0], halign)));
1383 parse2(cell->back(), FLAG_END, mode, false);
1386 else if (name == "tabular") {
1387 docstring const valign = parse_verbatim_option() + 'c';
1388 docstring const halign = parse_verbatim_item();
1389 cell->push_back(MathAtom(new InsetMathTabular(name,
1390 InsetMathGrid::guessColumns(halign), 1, (char)valign[0], halign)));
1391 parse2(cell->back(), FLAG_END, InsetMath::TEXT_MODE, false);
1394 else if (name == "split" || name == "cases") {
1395 cell->push_back(createInsetMath(name));
1396 parse2(cell->back(), FLAG_END, mode, false);
1399 else if (name == "alignedat") {
1400 docstring const valign = parse_verbatim_option() + 'c';
1401 // ignore this for a while
1403 cell->push_back(MathAtom(new InsetMathSplit(name, (char)valign[0])));
1404 parse2(cell->back(), FLAG_END, mode, false);
1407 else if (name == "math") {
1408 if (mode == InsetMath::MATH_MODE) {
1409 error("bad math environment");
1412 cell->push_back(MathAtom(new InsetMathHull(hullSimple)));
1413 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, true);
1416 else if (name == "equation" || name == "equation*"
1417 || name == "displaymath") {
1418 if (mode != InsetMath::UNDECIDED_MODE) {
1419 error("bad math environment");
1422 cell->push_back(MathAtom(new InsetMathHull(hullEquation)));
1423 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, (name == "equation"));
1426 else if (name == "eqnarray" || name == "eqnarray*") {
1427 if (mode != InsetMath::UNDECIDED_MODE) {
1428 error("bad math environment");
1431 cell->push_back(MathAtom(new InsetMathHull(hullEqnArray)));
1432 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, !stared(name));
1435 else if (name == "align" || name == "align*") {
1436 if (mode != InsetMath::UNDECIDED_MODE) {
1437 error("bad math environment");
1440 cell->push_back(MathAtom(new InsetMathHull(hullAlign)));
1441 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, !stared(name));
1444 else if (name == "flalign" || name == "flalign*") {
1445 if (mode != InsetMath::UNDECIDED_MODE) {
1446 error("bad math environment");
1449 cell->push_back(MathAtom(new InsetMathHull(hullFlAlign)));
1450 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, !stared(name));
1453 else if (name == "alignat" || name == "alignat*") {
1454 if (mode != InsetMath::UNDECIDED_MODE) {
1455 error("bad math environment");
1458 // ignore this for a while
1460 cell->push_back(MathAtom(new InsetMathHull(hullAlignAt)));
1461 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, !stared(name));
1464 else if (name == "xalignat" || name == "xalignat*") {
1465 if (mode != InsetMath::UNDECIDED_MODE) {
1466 error("bad math environment");
1469 // ignore this for a while
1471 cell->push_back(MathAtom(new InsetMathHull(hullXAlignAt)));
1472 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, !stared(name));
1475 else if (name == "xxalignat") {
1476 if (mode != InsetMath::UNDECIDED_MODE) {
1477 error("bad math environment");
1480 // ignore this for a while
1482 cell->push_back(MathAtom(new InsetMathHull(hullXXAlignAt)));
1483 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, !stared(name));
1486 else if (name == "multline" || name == "multline*") {
1487 if (mode != InsetMath::UNDECIDED_MODE) {
1488 error("bad math environment");
1491 cell->push_back(MathAtom(new InsetMathHull(hullMultline)));
1492 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, !stared(name));
1495 else if (name == "gather" || name == "gather*") {
1496 if (mode != InsetMath::UNDECIDED_MODE) {
1497 error("bad math environment");
1500 cell->push_back(MathAtom(new InsetMathHull(hullGather)));
1501 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, !stared(name));
1504 else if (latexkeys const * l = in_word_set(name)) {
1505 if (l->inset == "matrix") {
1506 cell->push_back(createInsetMath(name));
1507 parse2(cell->back(), FLAG_END, mode, false);
1508 } else if (l->inset == "split") {
1509 docstring const valign = parse_verbatim_option() + 'c';
1510 cell->push_back(MathAtom(new InsetMathSplit(name, (char)valign[0])));
1511 parse2(cell->back(), FLAG_END, mode, false);
1514 if (!(mode_ & Parse::QUIET)) {
1516 lyxerr << "found math environment `"
1518 << "' in symbols file with unsupported inset `"
1519 << to_utf8(l->inset)
1522 // create generic environment inset
1523 cell->push_back(MathAtom(new InsetMathEnv(name)));
1524 parse(cell->back().nucleus()->cell(0), FLAG_END, mode);
1530 if (!(mode_ & Parse::QUIET)) {
1532 lyxerr << "found unknown math environment '"
1533 << to_utf8(name) << "'" << endl;
1535 // create generic environment inset
1536 cell->push_back(MathAtom(new InsetMathEnv(name)));
1537 parse(cell->back().nucleus()->cell(0), FLAG_END, mode);
1541 else if (t.cs() == "kern") {
1545 Token const & t = getToken();
1551 if (isValidLength(to_utf8(s)))
1554 cell->push_back(MathAtom(new InsetMathKern(s)));
1557 else if (t.cs() == "label") {
1558 // FIXME: This is swallowed in inline formulas
1559 docstring label = parse_verbatim_item();
1562 if (grid.asHullInset()) {
1563 grid.asHullInset()->label(cellrow, label);
1565 cell->push_back(createInsetMath(t.cs()));
1566 cell->push_back(MathAtom(new InsetMathBrace(ar)));
1570 else if (t.cs() == "choose" || t.cs() == "over"
1571 || t.cs() == "atop" || t.cs() == "brace"
1572 || t.cs() == "brack") {
1573 MathAtom at = createInsetMath(t.cs());
1574 at.nucleus()->cell(0) = *cell;
1576 parse(at.nucleus()->cell(1), flags, mode);
1577 cell->push_back(at);
1581 else if (t.cs() == "color") {
1582 docstring const color = parse_verbatim_item();
1583 cell->push_back(MathAtom(new InsetMathColor(true, color)));
1584 parse(cell->back().nucleus()->cell(0), flags, mode);
1588 else if (t.cs() == "textcolor") {
1589 docstring const color = parse_verbatim_item();
1590 cell->push_back(MathAtom(new InsetMathColor(false, color)));
1591 parse(cell->back().nucleus()->cell(0), FLAG_ITEM, InsetMath::TEXT_MODE);
1594 else if (t.cs() == "normalcolor") {
1595 cell->push_back(createInsetMath(t.cs()));
1596 parse(cell->back().nucleus()->cell(0), flags, mode);
1600 else if (t.cs() == "substack") {
1601 cell->push_back(createInsetMath(t.cs()));
1602 parse2(cell->back(), FLAG_ITEM, mode, false);
1605 else if (t.cs() == "xymatrix") {
1606 odocstringstream os;
1607 while (good() && nextToken().cat() != catBegin)
1608 os << getToken().asInput();
1609 cell->push_back(createInsetMath(t.cs() + os.str()));
1610 parse2(cell->back(), FLAG_ITEM, mode, false);
1613 else if (t.cs() == "framebox" || t.cs() == "makebox") {
1614 cell->push_back(createInsetMath(t.cs()));
1615 parse(cell->back().nucleus()->cell(0), FLAG_OPTION, InsetMath::TEXT_MODE);
1616 parse(cell->back().nucleus()->cell(1), FLAG_OPTION, InsetMath::TEXT_MODE);
1617 parse(cell->back().nucleus()->cell(2), FLAG_ITEM, InsetMath::TEXT_MODE);
1620 else if (t.cs() == "tag") {
1621 if (nextToken().character() == '*') {
1623 cell->push_back(createInsetMath(t.cs() + '*'));
1625 cell->push_back(createInsetMath(t.cs()));
1626 parse(cell->back().nucleus()->cell(0), FLAG_ITEM, InsetMath::TEXT_MODE);
1629 else if (t.cs() == "hspace" && nextToken().character() != '*') {
1630 docstring const name = t.cs();
1631 docstring const arg = parse_verbatim_item();
1633 if (isValidLength(to_utf8(arg), &length))
1634 cell->push_back(MathAtom(new InsetMathSpace(length)));
1636 // Since the Length class cannot use length variables
1637 // we must not create an InsetMathSpace.
1638 cell->push_back(MathAtom(new MathMacro(name)));
1640 mathed_parse_cell(ar, '{' + arg + '}');
1646 else if (t.cs() == "infer") {
1648 parse(ar, FLAG_OPTION, mode);
1649 cell->push_back(createInsetMath(t.cs()));
1650 parse2(cell->back(), FLAG_ITEM, mode, false);
1654 else if (1 && t.cs() == "ar") {
1655 auto_ptr<InsetMathXYArrow> p(new InsetMathXYArrow);
1656 // try to read target
1657 parse(p->cell(0), FLAG_OTPTION, mode);
1658 // try to read label
1659 if (nextToken().cat() == catSuper || nextToken().cat() == catSub) {
1660 p->up_ = nextToken().cat() == catSuper;
1662 parse(p->cell(1), FLAG_ITEM, mode);
1663 //lyxerr << "read label: " << p->cell(1) << endl;
1666 cell->push_back(MathAtom(p.release()));
1667 //lyxerr << "read cell: " << cell << endl;
1671 else if (t.cs() == "lyxmathsym") {
1673 if (getToken().cat() != catBegin) {
1674 error("'{' expected in \\" + t.cs());
1679 CatCode cat = nextToken().cat();
1680 while (good() && (count || cat != catEnd)) {
1681 if (cat == catBegin)
1683 else if (cat == catEnd)
1685 cmd += getToken().asInput();
1686 cat = nextToken().cat();
1688 if (getToken().cat() != catEnd) {
1689 error("'}' expected in \\" + t.cs());
1694 cmd = Encodings::fromLaTeXCommand(cmd, rem);
1695 for (size_t i = 0; i < cmd.size(); ++i)
1696 cell->push_back(MathAtom(new InsetMathChar(cmd[i])));
1698 char_type c = rem[0];
1699 cell->push_back(MathAtom(new InsetMathChar(c)));
1700 cmd = rem.substr(1);
1704 } while (cmd.size());
1707 else if (t.cs().size()) {
1708 latexkeys const * l = in_word_set(t.cs());
1710 if (l->inset == "big") {
1712 docstring const delim = getToken().asInput();
1713 if (InsetMathBig::isBigInsetDelim(delim))
1714 cell->push_back(MathAtom(
1715 new InsetMathBig(t.cs(), delim)));
1717 cell->push_back(createInsetMath(t.cs()));
1722 else if (l->inset == "font") {
1723 cell->push_back(createInsetMath(t.cs()));
1724 parse(cell->back().nucleus()->cell(0),
1725 FLAG_ITEM, asMode(mode, l->extra));
1728 else if (l->inset == "oldfont") {
1729 cell->push_back(createInsetMath(t.cs()));
1730 parse(cell->back().nucleus()->cell(0),
1731 flags | FLAG_ALIGN, asMode(mode, l->extra));
1732 if (prevToken().cat() != catAlign &&
1733 prevToken().cs() != "\\")
1738 else if (l->inset == "style") {
1739 cell->push_back(createInsetMath(t.cs()));
1740 parse(cell->back().nucleus()->cell(0),
1741 flags | FLAG_ALIGN, mode);
1742 if (prevToken().cat() != catAlign &&
1743 prevToken().cs() != "\\")
1749 MathAtom at = createInsetMath(t.cs());
1750 for (InsetMath::idx_type i = 0; i < at->nargs(); ++i)
1751 parse(at.nucleus()->cell(i),
1752 FLAG_ITEM, asMode(mode, l->extra));
1753 cell->push_back(at);
1758 bool is_unicode_symbol = false;
1759 if (mode == InsetMath::TEXT_MODE) {
1761 docstring cmd = prevToken().asInput();
1763 CatCode cat = nextToken().cat();
1764 if (cat == catBegin) {
1766 while (good() && (count || cat != catEnd)) {
1767 cat = nextToken().cat();
1768 cmd += getToken().asInput();
1770 if (cat == catBegin)
1772 else if (cat == catEnd)
1778 Encodings::fromLaTeXCommand(cmd, is_combining);
1780 if (cat == catLetter)
1782 cmd += getToken().asInput();
1784 if (cat == catLetter)
1786 c = Encodings::fromLaTeXCommand(cmd, is_combining);
1789 is_unicode_symbol = true;
1790 cell->push_back(MathAtom(new InsetMathChar(c)));
1792 while (num_tokens--)
1796 if (!is_unicode_symbol) {
1797 MathAtom at = createInsetMath(t.cs());
1798 InsetMath::mode_type m = mode;
1799 //if (m == InsetMath::UNDECIDED_MODE)
1800 //lyxerr << "default creation: m1: " << m << endl;
1801 if (at->currentMode() != InsetMath::UNDECIDED_MODE)
1802 m = at->currentMode();
1803 //lyxerr << "default creation: m2: " << m << endl;
1804 InsetMath::idx_type start = 0;
1805 // this fails on \bigg[...\bigg]
1807 //parse(opt, FLAG_OPTION, InsetMath::VERBATIM_MODE);
1810 // at.nucleus()->cell(0) = opt;
1812 for (InsetMath::idx_type i = start; i < at->nargs(); ++i) {
1813 parse(at.nucleus()->cell(i), FLAG_ITEM, m);
1816 cell->push_back(at);
1822 if (flags & FLAG_LEAVE) {
1823 flags &= ~FLAG_LEAVE;
1832 } // anonymous namespace
1835 bool mathed_parse_cell(MathData & ar, docstring const & str, Parse::flags f)
1837 return Parser(str, f).parse(ar, 0, f & Parse::TEXTMODE ?
1838 InsetMath::TEXT_MODE : InsetMath::MATH_MODE);
1842 bool mathed_parse_cell(MathData & ar, istream & is, Parse::flags f)
1844 return Parser(is, f).parse(ar, 0, f & Parse::TEXTMODE ?
1845 InsetMath::TEXT_MODE : InsetMath::MATH_MODE);
1849 bool mathed_parse_normal(MathAtom & t, docstring const & str, Parse::flags f)
1851 return Parser(str, f).parse(t);
1855 bool mathed_parse_normal(MathAtom & t, Lexer & lex, Parse::flags f)
1857 return Parser(lex, f).parse(t);
1861 bool mathed_parse_normal(InsetMathGrid & grid, docstring const & str, Parse::flags f)
1863 return Parser(str, f).parse1(grid, 0, f & Parse::TEXTMODE ?
1864 InsetMath::TEXT_MODE : InsetMath::MATH_MODE, false);
1870 fill(theCatcode, theCatcode + 128, catOther);
1871 fill(theCatcode + 'a', theCatcode + 'z' + 1, catLetter);
1872 fill(theCatcode + 'A', theCatcode + 'Z' + 1, catLetter);
1874 theCatcode[int('\\')] = catEscape;
1875 theCatcode[int('{')] = catBegin;
1876 theCatcode[int('}')] = catEnd;
1877 theCatcode[int('$')] = catMath;
1878 theCatcode[int('&')] = catAlign;
1879 theCatcode[int('\n')] = catNewline;
1880 theCatcode[int('#')] = catParameter;
1881 theCatcode[int('^')] = catSuper;
1882 theCatcode[int('_')] = catSub;
1883 theCatcode[int(0x7f)] = catIgnore;
1884 theCatcode[int(' ')] = catSpace;
1885 theCatcode[int('\t')] = catSpace;
1886 theCatcode[int('\r')] = catNewline;
1887 theCatcode[int('~')] = catActive;
1888 theCatcode[int('%')] = catComment;