]> git.lyx.org Git - features.git/blob - src/mathed/MathParser.cpp
Fix bug #7183 (User math macros defined in child documents are shadowed on loading)
[features.git] / src / mathed / MathParser.cpp
1 /**
2  * \file MathParser.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author André Pönitz
7  *
8  * Full author contact details are available in file CREDITS.
9  */
10
11 /*
12
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:
16
17   \newif\ifcomment
18   \commentfalse
19   \ifcomment
20           \def\makeamptab{\catcode`\&=4\relax}
21           \def\makeampletter{\catcode`\&=11\relax}
22     \def\b{\makeampletter\expandafter\makeamptab\bi}
23     \long\def\bi#1\e{}
24   \else
25     \def\b{}\def\e{}
26   \fi
27   ...
28
29   \[\begin{array}{ccc}
30 1
31 &
32
33   \end{array}\]
34
35 */
36
37
38 #include <config.h>
39
40 #include "MathParser.h"
41
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 "InsetMathEnsureMath.h"
50 #include "InsetMathEnv.h"
51 #include "InsetMathFrac.h"
52 #include "InsetMathKern.h"
53 #include "MathMacro.h"
54 #include "InsetMathPar.h"
55 #include "InsetMathRef.h"
56 #include "InsetMathRoot.h"
57 #include "InsetMathScript.h"
58 #include "InsetMathSpace.h"
59 #include "InsetMathSplit.h"
60 #include "InsetMathSqrt.h"
61 #include "InsetMathString.h"
62 #include "InsetMathTabular.h"
63 #include "MathMacroTemplate.h"
64 #include "MathFactory.h"
65 #include "MathMacroArgument.h"
66 #include "MathSupport.h"
67
68 #include "Buffer.h"
69 #include "BufferParams.h"
70 #include "Encoding.h"
71 #include "Lexer.h"
72
73 #include "support/debug.h"
74 #include "support/convert.h"
75 #include "support/docstream.h"
76
77 #include <sstream>
78
79 //#define FILEDEBUG
80
81 using namespace std;
82
83 namespace lyx {
84
85 namespace {
86
87 InsetMath::mode_type asMode(InsetMath::mode_type oldmode, docstring const & str)
88 {
89         //lyxerr << "handling mode: '" << str << "'" << endl;
90         if (str == "mathmode")
91                 return InsetMath::MATH_MODE;
92         if (str == "textmode" || str == "forcetext")
93                 return InsetMath::TEXT_MODE;
94         return oldmode;
95 }
96
97
98 bool stared(docstring const & s)
99 {
100         size_t const n = s.size();
101         return n && s[n - 1] == '*';
102 }
103
104
105 docstring const repl(docstring const & oldstr, char_type const c,
106                      docstring const & macro, bool textmode = false)
107 {
108         docstring newstr;
109         size_t i;
110         size_t j;
111
112         for (i = 0, j = 0; i < oldstr.size(); ++i) {
113                 if (c == oldstr[i]) {
114                         newstr.append(oldstr, j, i - j);
115                         newstr.append(macro);
116                         j = i + 1;
117                         if (macro.size() > 2 && j < oldstr.size())
118                                 newstr += (textmode && oldstr[j] == ' ' ? '\\' : ' ');
119                 }
120         }
121
122         // Any substitution?
123         if (j == 0)
124                 return oldstr;
125
126         newstr.append(oldstr, j, i - j);
127         return newstr;
128 }
129
130
131 docstring escapeSpecialChars(docstring const & str, bool textmode)
132 {
133         docstring const backslash = textmode ? from_ascii("\\textbackslash")
134                                              : from_ascii("\\backslash");
135         docstring const caret = textmode ? from_ascii("\\textasciicircum")
136                                          : from_ascii("\\mathcircumflex");
137         docstring const tilde = textmode ? from_ascii("\\textasciitilde")
138                                          : from_ascii("\\sim");
139
140         return repl(repl(repl(repl(repl(repl(repl(repl(repl(repl(str,
141                         '\\', backslash, textmode),
142                         '^', caret, textmode),
143                         '~', tilde, textmode),
144                         '_', from_ascii("\\_")),
145                         '$', from_ascii("\\$")),
146                         '#', from_ascii("\\#")),
147                         '&', from_ascii("\\&")),
148                         '%', from_ascii("\\%")),
149                         '{', from_ascii("\\{")),
150                         '}', from_ascii("\\}"));
151 }
152
153
154 /*!
155  * Add the row \p cellrow to \p grid.
156  * \returns wether the row could be added. Adding a row can fail for
157  * environments like "equation" that have a fixed number of rows.
158  */
159 bool addRow(InsetMathGrid & grid, InsetMathGrid::row_type & cellrow,
160             docstring const & vskip, bool allow_newpage_ = true)
161 {
162         ++cellrow;
163         if (cellrow == grid.nrows()) {
164                 //lyxerr << "adding row " << cellrow << endl;
165                 grid.addRow(cellrow - 1);
166                 if (cellrow == grid.nrows()) {
167                         // We can't add a row to this grid, so let's
168                         // append the content of this cell to the previous
169                         // one.
170                         // This does not happen in well formed .lyx files,
171                         // but LyX versions 1.3.x and older could create
172                         // such files and tex2lyx can still do that.
173                         --cellrow;
174                         lyxerr << "ignoring extra row";
175                         if (!vskip.empty())
176                                 lyxerr << " with extra space " << to_utf8(vskip);
177                         if (!allow_newpage_)
178                                 lyxerr << " with no page break allowed";
179                         lyxerr << '.' << endl;
180                         return false;
181                 }
182         }
183         grid.vcrskip(Length(to_utf8(vskip)), cellrow - 1);
184         grid.rowinfo(cellrow - 1).allow_newpage_ = allow_newpage_;
185         return true;
186 }
187
188
189 /*!
190  * Add the column \p cellcol to \p grid.
191  * \returns wether the column could be added. Adding a column can fail for
192  * environments like "eqnarray" that have a fixed number of columns.
193  */
194 bool addCol(InsetMathGrid & grid, InsetMathGrid::col_type & cellcol)
195 {
196         ++cellcol;
197         if (cellcol == grid.ncols()) {
198                 //lyxerr << "adding column " << cellcol << endl;
199                 grid.addCol(cellcol);
200                 if (cellcol == grid.ncols()) {
201                         // We can't add a column to this grid, so let's
202                         // append the content of this cell to the previous
203                         // one.
204                         // This does not happen in well formed .lyx files,
205                         // but LyX versions 1.3.x and older could create
206                         // such files and tex2lyx can still do that.
207                         --cellcol;
208                         lyxerr << "ignoring extra column." << endl;
209                         return false;
210                 }
211         }
212         return true;
213 }
214
215
216 /*!
217  * Check whether the last row is empty and remove it if yes.
218  * Otherwise the following code
219  * \verbatim
220 \begin{array}{|c|c|}
221 \hline
222 1 & 2 \\ \hline
223 3 & 4 \\ \hline
224 \end{array}
225  * \endverbatim
226  * will result in a grid with 3 rows (+ the dummy row that is always present),
227  * because the last '\\' opens a new row.
228  * Note that this is only needed for inner-hull grid types, such as array
229  * or aligned, but not for outer-hull grid types, such as eqnarray or align.
230  */
231 void delEmptyLastRow(InsetMathGrid & grid)
232 {
233         InsetMathGrid::row_type const row = grid.nrows() - 1;
234         for (InsetMathGrid::col_type col = 0; col < grid.ncols(); ++col) {
235                 if (!grid.cell(grid.index(row, col)).empty())
236                         return;
237         }
238         // Copy the row information of the empty row (which would contain the
239         // last hline in the example above) to the dummy row and delete the
240         // empty row.
241         grid.rowinfo(row + 1) = grid.rowinfo(row);
242         grid.delRow(row);
243 }
244
245
246 /*!
247  * Tell whether the environment name corresponds to an inner-hull grid type.
248  */
249 bool innerHull(docstring const & name)
250 {
251         // For [bB]matrix, [vV]matrix, and pmatrix we can check the suffix only
252         return name == "array" || name == "cases" || name == "aligned"
253                 || name == "alignedat" || name == "gathered" || name == "split"
254                 || name == "subarray" || name == "tabular" || name == "matrix"
255                 || name.substr(1) == "matrix";
256 }
257
258
259 // These are TeX's catcodes
260 enum CatCode {
261         catEscape,     // 0    backslash
262         catBegin,      // 1    {
263         catEnd,        // 2    }
264         catMath,       // 3    $
265         catAlign,      // 4    &
266         catNewline,    // 5    ^^M
267         catParameter,  // 6    #
268         catSuper,      // 7    ^
269         catSub,        // 8    _
270         catIgnore,     // 9
271         catSpace,      // 10   space
272         catLetter,     // 11   a-zA-Z
273         catOther,      // 12   none of the above
274         catActive,     // 13   ~
275         catComment,    // 14   %
276         catInvalid     // 15   <delete>
277 };
278
279 CatCode theCatcode[128];
280
281
282 inline CatCode catcode(char_type c)
283 {
284         /* The only characters that are not catOther lie in the pure ASCII
285          * range. Therefore theCatcode has only 128 entries.
286          * TeX itself deals with 8bit characters, so if needed this table
287          * could be enlarged to 256 entries.
288          * Any larger value does not make sense, since the fact that we use
289          * unicode internally does not change Knuth's TeX engine.
290          * Apart from that a table for the full 21bit UCS4 range would waste
291          * too much memory. */
292         if (c >= 128)
293                 return catOther;
294
295         return theCatcode[c];
296 }
297
298
299 enum {
300         FLAG_ALIGN      = 1 << 0,  //  next & or \\ ends the parsing process
301         FLAG_BRACE_LAST = 1 << 1,  //  next closing brace ends the parsing
302         FLAG_RIGHT      = 1 << 2,  //  next \\right ends the parsing process
303         FLAG_END        = 1 << 3,  //  next \\end ends the parsing process
304         FLAG_BRACK_LAST = 1 << 4,  //  next closing bracket ends the parsing
305         FLAG_TEXTMODE   = 1 << 5,  //  we are in a box
306         FLAG_ITEM       = 1 << 6,  //  read a (possibly braced) token
307         FLAG_LEAVE      = 1 << 7,  //  leave the loop at the end
308         FLAG_SIMPLE     = 1 << 8,  //  next $ leaves the loop
309         FLAG_EQUATION   = 1 << 9,  //  next \] leaves the loop
310         FLAG_SIMPLE2    = 1 << 10, //  next \) leaves the loop
311         FLAG_OPTION     = 1 << 11, //  read [...] style option
312         FLAG_BRACED     = 1 << 12  //  read {...} style argument
313 };
314
315
316 //
317 // Helper class for parsing
318 //
319
320 class Token {
321 public:
322         ///
323         Token() : cs_(), char_(0), cat_(catIgnore) {}
324         ///
325         Token(char_type c, CatCode cat) : cs_(), char_(c), cat_(cat) {}
326         ///
327         explicit Token(docstring const & cs) : cs_(cs), char_(0), cat_(catIgnore) {}
328
329         ///
330         docstring const & cs() const { return cs_; }
331         ///
332         CatCode cat() const { return cat_; }
333         ///
334         char_type character() const { return char_; }
335         ///
336         docstring asString() const { return cs_.size() ? cs_ : docstring(1, char_); }
337         ///
338         docstring asInput() const { return cs_.size() ? '\\' + cs_ : docstring(1, char_); }
339
340 private:
341         ///
342         docstring cs_;
343         ///
344         char_type char_;
345         ///
346         CatCode cat_;
347 };
348
349
350 ostream & operator<<(ostream & os, Token const & t)
351 {
352         if (t.cs().size()) {
353                 docstring const & cs = t.cs();
354                 // FIXME: For some strange reason, the stream operator instanciate
355                 // a new Token before outputting the contents of t.cs().
356                 // Because of this the line
357                 //     os << '\\' << cs;
358                 // below becomes recursive.
359                 // In order to avoid that we return early:
360                 if (cs == "\\")
361                         return os;
362                 os << '\\' << to_utf8(cs);
363         }
364         else if (t.cat() == catLetter)
365                 os << t.character();
366         else
367                 os << '[' << t.character() << ',' << t.cat() << ']';
368         return os;
369 }
370
371
372 class Parser {
373 public:
374         ///
375         typedef  InsetMath::mode_type mode_type;
376         ///
377         typedef  Parse::flags parse_mode;
378
379         ///
380         Parser(Lexer & lex, parse_mode mode, Buffer * buf);
381         /// Only use this for reading from .lyx file format, for the reason
382         /// see Parser::tokenize(istream &).
383         Parser(istream & is, parse_mode mode, Buffer * buf);
384         ///
385         Parser(docstring const & str, parse_mode mode, Buffer * buf);
386
387         ///
388         bool parse(MathAtom & at);
389         ///
390         bool parse(MathData & array, unsigned flags, mode_type mode);
391         ///
392         bool parse1(InsetMathGrid & grid, unsigned flags, mode_type mode,
393                 bool numbered);
394         ///
395         MathData parse(unsigned flags, mode_type mode);
396         ///
397         int lineno() const { return lineno_; }
398         ///
399         void putback();
400
401 private:
402         ///
403         void parse2(MathAtom & at, unsigned flags, mode_type mode, bool numbered);
404         /// get arg delimited by 'left' and 'right'
405         docstring getArg(char_type left, char_type right);
406         ///
407         char_type getChar();
408         ///
409         void error(string const & msg);
410         void error(docstring const & msg) { error(to_utf8(msg)); }
411         /// dump contents to screen
412         void dump() const;
413         /// Only use this for reading from .lyx file format (see
414         /// implementation for reason)
415         void tokenize(istream & is);
416         ///
417         void tokenize(docstring const & s);
418         ///
419         void skipSpaceTokens(idocstream & is, char_type c);
420         ///
421         void push_back(Token const & t);
422         ///
423         void pop_back();
424         ///
425         Token const & prevToken() const;
426         ///
427         Token const & nextToken() const;
428         ///
429         Token const & getToken();
430         /// skips spaces if any
431         void skipSpaces();
432         ///
433         void lex(docstring const & s);
434         ///
435         bool good() const;
436         ///
437         docstring parse_verbatim_item();
438         ///
439         docstring parse_verbatim_option();
440
441         ///
442         int lineno_;
443         ///
444         vector<Token> tokens_;
445         ///
446         unsigned pos_;
447         /// Stack of active environments
448         vector<docstring> environments_;
449         ///
450         parse_mode mode_;
451         ///
452         bool success_;
453         ///
454         Buffer * buffer_;
455 };
456
457
458 Parser::Parser(Lexer & lexer, parse_mode mode, Buffer * buf)
459         : lineno_(lexer.lineNumber()), pos_(0), mode_(mode), success_(true),
460           buffer_(buf)
461 {
462         tokenize(lexer.getStream());
463         lexer.eatLine();
464 }
465
466
467 Parser::Parser(istream & is, parse_mode mode, Buffer * buf)
468         : lineno_(0), pos_(0), mode_(mode), success_(true), buffer_(buf)
469 {
470         tokenize(is);
471 }
472
473
474 Parser::Parser(docstring const & str, parse_mode mode, Buffer * buf)
475         : lineno_(0), pos_(0), mode_(mode), success_(true), buffer_(buf)
476 {
477         tokenize(str);
478 }
479
480
481 void Parser::push_back(Token const & t)
482 {
483         tokens_.push_back(t);
484 }
485
486
487 void Parser::pop_back()
488 {
489         tokens_.pop_back();
490 }
491
492
493 Token const & Parser::prevToken() const
494 {
495         static const Token dummy;
496         return pos_ > 0 ? tokens_[pos_ - 1] : dummy;
497 }
498
499
500 Token const & Parser::nextToken() const
501 {
502         static const Token dummy;
503         return good() ? tokens_[pos_] : dummy;
504 }
505
506
507 Token const & Parser::getToken()
508 {
509         static const Token dummy;
510         //lyxerr << "looking at token " << tokens_[pos_] << " pos: " << pos_ << endl;
511         return good() ? tokens_[pos_++] : dummy;
512 }
513
514
515 void Parser::skipSpaces()
516 {
517         while (nextToken().cat() == catSpace || nextToken().cat() == catNewline)
518                 getToken();
519 }
520
521
522 void Parser::putback()
523 {
524         --pos_;
525 }
526
527
528 bool Parser::good() const
529 {
530         return pos_ < tokens_.size();
531 }
532
533
534 char_type Parser::getChar()
535 {
536         if (!good()) {
537                 error("The input stream is not well...");
538                 putback();
539                 return 0;
540         }
541         return tokens_[pos_++].character();
542 }
543
544
545 docstring Parser::getArg(char_type left, char_type right)
546 {
547         skipSpaces();
548
549         docstring result;
550         char_type c = getChar();
551
552         if (c != left)
553                 putback();
554         else
555                 while ((c = getChar()) != right && good())
556                         result += c;
557
558         return result;
559 }
560
561
562 void Parser::skipSpaceTokens(idocstream & is, char_type c)
563 {
564         // skip trailing spaces
565         while (catcode(c) == catSpace || catcode(c) == catNewline)
566                 if (!is.get(c))
567                         break;
568         //lyxerr << "putting back: " << c << endl;
569         is.putback(c);
570 }
571
572
573 void Parser::tokenize(istream & is)
574 {
575         // eat everything up to the next \end_inset or end of stream
576         // and store it in s for further tokenization
577         string s;
578         char c;
579         while (is.get(c)) {
580                 s += c;
581                 if (s.size() >= 10 && s.substr(s.size() - 10) == "\\end_inset") {
582                         s = s.substr(0, s.size() - 10);
583                         break;
584                 }
585         }
586         // Remove the space after \end_inset
587         if (is.get(c) && c != ' ')
588                 is.unget();
589
590         // tokenize buffer
591         tokenize(from_utf8(s));
592 }
593
594
595 void Parser::tokenize(docstring const & buffer)
596 {
597         idocstringstream is(mode_ & Parse::VERBATIM
598                         ? escapeSpecialChars(buffer, mode_ & Parse::TEXTMODE)
599                         : buffer, ios::in | ios::binary);
600
601         char_type c;
602         while (is.get(c)) {
603                 //lyxerr << "reading c: " << c << endl;
604
605                 switch (catcode(c)) {
606                         case catNewline: {
607                                 ++lineno_;
608                                 is.get(c);
609                                 if (catcode(c) == catNewline)
610                                         ; //push_back(Token("par"));
611                                 else {
612                                         push_back(Token('\n', catNewline));
613                                         is.putback(c);
614                                 }
615                                 break;
616                         }
617
618 /*
619                         case catComment: {
620                                 while (is.get(c) && catcode(c) != catNewline)
621                                         ;
622                                 ++lineno_;
623                                 break;
624                         }
625 */
626
627                         case catEscape: {
628                                 is.get(c);
629                                 if (!is) {
630                                         error("unexpected end of input");
631                                 } else {
632                                         if (c == '\n')
633                                                 c = ' ';
634                                         docstring s(1, c);
635                                         if (catcode(c) == catLetter) {
636                                                 // collect letters
637                                                 while (is.get(c) && catcode(c) == catLetter)
638                                                         s += c;
639                                                 skipSpaceTokens(is, c);
640                                         }
641                                         push_back(Token(s));
642                                 }
643                                 break;
644                         }
645
646                         case catSuper:
647                         case catSub: {
648                                 push_back(Token(c, catcode(c)));
649                                 is.get(c);
650                                 skipSpaceTokens(is, c);
651                                 break;
652                         }
653
654                         case catIgnore: {
655                                 if (!(mode_ & Parse::QUIET))
656                                         lyxerr << "ignoring a char: " << int(c) << endl;
657                                 break;
658                         }
659
660                         default:
661                                 push_back(Token(c, catcode(c)));
662                 }
663         }
664
665 #ifdef FILEDEBUG
666         dump();
667 #endif
668 }
669
670
671 void Parser::dump() const
672 {
673         lyxerr << "\nTokens: ";
674         for (unsigned i = 0; i < tokens_.size(); ++i) {
675                 if (i == pos_)
676                         lyxerr << " <#> ";
677                 lyxerr << tokens_[i];
678         }
679         lyxerr << " pos: " << pos_ << endl;
680 }
681
682
683 void Parser::error(string const & msg)
684 {
685         success_ = false;
686         if (!(mode_ & Parse::QUIET)) {
687                 lyxerr << "Line ~" << lineno_ << ": Math parse error: "
688                        << msg << endl;
689                 dump();
690         }
691 }
692
693
694 bool Parser::parse(MathAtom & at)
695 {
696         skipSpaces();
697         MathData ar(buffer_);
698         parse(ar, false, InsetMath::UNDECIDED_MODE);
699         if (ar.size() != 1 || ar.front()->getType() == hullNone) {
700                 if (!(mode_ & Parse::QUIET))
701                         lyxerr << "unusual contents found: " << ar << endl;
702                 at = MathAtom(new InsetMathPar(buffer_, ar));
703                 //if (at->nargs() > 0)
704                 //      at.nucleus()->cell(0) = ar;
705                 //else
706                 //      lyxerr << "unusual contents found: " << ar << endl;
707                 success_ = false;
708         } else
709                 at = ar[0];
710         return success_;
711 }
712
713
714 docstring Parser::parse_verbatim_option()
715 {
716         skipSpaces();
717         docstring res;
718         if (nextToken().character() == '[') {
719                 Token t = getToken();
720                 for (Token t = getToken(); t.character() != ']' && good(); t = getToken()) {
721                         if (t.cat() == catBegin) {
722                                 putback();
723                                 res += '{' + parse_verbatim_item() + '}';
724                         } else
725                                 res += t.asInput();
726                 }
727         }
728         return res;
729 }
730
731
732 docstring Parser::parse_verbatim_item()
733 {
734         skipSpaces();
735         docstring res;
736         if (nextToken().cat() == catBegin) {
737                 Token t = getToken();
738                 for (Token t = getToken(); t.cat() != catEnd && good(); t = getToken()) {
739                         if (t.cat() == catBegin) {
740                                 putback();
741                                 res += '{' + parse_verbatim_item() + '}';
742                         }
743                         else
744                                 res += t.asInput();
745                 }
746         }
747         return res;
748 }
749
750
751 MathData Parser::parse(unsigned flags, mode_type mode)
752 {
753         MathData ar(buffer_);
754         parse(ar, flags, mode);
755         return ar;
756 }
757
758
759 bool Parser::parse(MathData & array, unsigned flags, mode_type mode)
760 {
761         InsetMathGrid grid(buffer_, 1, 1);
762         parse1(grid, flags, mode, false);
763         array = grid.cell(0);
764         return success_;
765 }
766
767
768 void Parser::parse2(MathAtom & at, const unsigned flags, const mode_type mode,
769         const bool numbered)
770 {
771         parse1(*(at.nucleus()->asGridInset()), flags, mode, numbered);
772 }
773
774
775 bool Parser::parse1(InsetMathGrid & grid, unsigned flags,
776         const mode_type mode, const bool numbered)
777 {
778         int limits = 0;
779         InsetMathGrid::row_type cellrow = 0;
780         InsetMathGrid::col_type cellcol = 0;
781         MathData * cell = &grid.cell(grid.index(cellrow, cellcol));
782         Buffer * buf = buffer_;
783
784         if (grid.asHullInset())
785                 grid.asHullInset()->numbered(cellrow, numbered);
786
787         //dump();
788         //lyxerr << " flags: " << flags << endl;
789         //lyxerr << " mode: " << mode  << endl;
790         //lyxerr << "grid: " << grid << endl;
791
792         while (good()) {
793                 Token const & t = getToken();
794
795 #ifdef FILEDEBUG
796                 lyxerr << "t: " << t << " flags: " << flags << endl;
797                 lyxerr << "mode: " << mode  << endl;
798                 cell->dump();
799                 lyxerr << endl;
800 #endif
801
802                 if (flags & FLAG_ITEM) {
803
804                         if (t.cat() == catBegin) {
805                                 // skip the brace and collect everything to the next matching
806                                 // closing brace
807                                 parse1(grid, FLAG_BRACE_LAST, mode, numbered);
808                                 return success_;
809                         }
810
811                         // handle only this single token, leave the loop if done
812                         flags = FLAG_LEAVE;
813                 }
814
815
816                 if (flags & FLAG_BRACED) {
817                         if (t.cat() == catSpace)
818                                 continue;
819
820                         if (t.cat() != catBegin) {
821                                 error("opening brace expected");
822                                 return success_;
823                         }
824
825                         // skip the brace and collect everything to the next matching
826                         // closing brace
827                         flags = FLAG_BRACE_LAST;
828                 }
829
830
831                 if (flags & FLAG_OPTION) {
832                         if (t.cat() == catOther && t.character() == '[') {
833                                 MathData ar;
834                                 parse(ar, FLAG_BRACK_LAST, mode);
835                                 cell->append(ar);
836                         } else {
837                                 // no option found, put back token and we are done
838                                 putback();
839                         }
840                         return success_;
841                 }
842
843                 //
844                 // cat codes
845                 //
846                 if (t.cat() == catMath) {
847                         if (mode != InsetMath::MATH_MODE) {
848                                 // we are inside some text mode thingy, so opening new math is allowed
849                                 Token const & n = getToken();
850                                 if (n.cat() == catMath) {
851                                         // TeX's $$...$$ syntax for displayed math
852                                         if (mode == InsetMath::UNDECIDED_MODE) {
853                                                 cell->push_back(MathAtom(new InsetMathHull(buf, hullEquation)));
854                                                 parse2(cell->back(), FLAG_SIMPLE, InsetMath::MATH_MODE, false);
855                                                 getToken(); // skip the second '$' token
856                                         } else {
857                                                 // This is not an outer hull and display math is
858                                                 // not allowed inside text mode environments.
859                                                 error("bad math environment");
860                                                 break;
861                                         }
862                                 } else {
863                                         // simple $...$  stuff
864                                         putback();
865                                         if (mode == InsetMath::UNDECIDED_MODE) {
866                                                 cell->push_back(MathAtom(new InsetMathHull(buf, hullSimple)));
867                                                 parse2(cell->back(), FLAG_SIMPLE, InsetMath::MATH_MODE, false);
868                                         } else {
869                                                 // Don't create nested math hulls (bug #5392)
870                                                 cell->push_back(MathAtom(new InsetMathEnsureMath(buf)));
871                                                 parse(cell->back().nucleus()->cell(0), FLAG_SIMPLE, InsetMath::MATH_MODE);
872                                         }
873                                 }
874                         }
875
876                         else if (flags & FLAG_SIMPLE) {
877                                 // this is the end of the formula
878                                 return success_;
879                         }
880
881                         else {
882                                 Token const & n = getToken();
883                                 if (n.cat() == catMath) {
884                                         error("something strange in the parser");
885                                         break;
886                                 } else {
887                                         // This is inline math ($...$), but the parser thinks we are
888                                         // already in math mode and latex would issue an error, unless we
889                                         // are inside a text mode user macro. We have no way to tell, so
890                                         // let's play safe by using \ensuremath, as it will work in any case.
891                                         putback();
892                                         cell->push_back(MathAtom(new InsetMathEnsureMath(buf)));
893                                         parse(cell->back().nucleus()->cell(0), FLAG_SIMPLE, InsetMath::MATH_MODE);
894                                 }
895                         }
896                 }
897
898                 else if (t.cat() == catLetter)
899                         cell->push_back(MathAtom(new InsetMathChar(t.character())));
900
901                 else if (t.cat() == catSpace && mode != InsetMath::MATH_MODE) {
902                         if (cell->empty() || cell->back()->getChar() != ' ')
903                                 cell->push_back(MathAtom(new InsetMathChar(t.character())));
904                 }
905
906                 else if (t.cat() == catNewline && mode != InsetMath::MATH_MODE) {
907                         if (cell->empty() || cell->back()->getChar() != ' ')
908                                 cell->push_back(MathAtom(new InsetMathChar(' ')));
909                 }
910
911                 else if (t.cat() == catParameter) {
912                         Token const & n = getToken();
913                         cell->push_back(MathAtom(new MathMacroArgument(n.character()-'0')));
914                 }
915
916                 else if (t.cat() == catActive)
917                         cell->push_back(MathAtom(new InsetMathChar(t.character())));
918
919                 else if (t.cat() == catBegin) {
920                         MathData ar;
921                         parse(ar, FLAG_BRACE_LAST, mode);
922                         // do not create a BraceInset if they were written by LyX
923                         // this helps to keep the annoyance of  "a choose b"  to a minimum
924                         if (ar.size() == 1 && ar[0]->extraBraces())
925                                 cell->append(ar);
926                         else
927                                 cell->push_back(MathAtom(new InsetMathBrace(ar)));
928                 }
929
930                 else if (t.cat() == catEnd) {
931                         if (flags & FLAG_BRACE_LAST)
932                                 return success_;
933                         error("found '}' unexpectedly");
934                         //LASSERT(false, /**/);
935                         //add(cell, '}', LM_TC_TEX);
936                 }
937
938                 else if (t.cat() == catAlign) {
939                         //lyxerr << " column now " << (cellcol + 1)
940                         //       << " max: " << grid.ncols() << endl;
941                         if (flags & FLAG_ALIGN)
942                                 return success_;
943                         if (addCol(grid, cellcol))
944                                 cell = &grid.cell(grid.index(cellrow, cellcol));
945                 }
946
947                 else if (t.cat() == catSuper || t.cat() == catSub) {
948                         bool up = (t.cat() == catSuper);
949                         // we need no new script inset if the last thing was a scriptinset,
950                         // which has that script already not the same script already
951                         if (!cell->size())
952                                 cell->push_back(MathAtom(new InsetMathScript(buf, up)));
953                         else if (cell->back()->asScriptInset() &&
954                                         !cell->back()->asScriptInset()->has(up))
955                                 cell->back().nucleus()->asScriptInset()->ensure(up);
956                         else if (cell->back()->asScriptInset())
957                                 cell->push_back(MathAtom(new InsetMathScript(buf, up)));
958                         else
959                                 cell->back() = MathAtom(new InsetMathScript(buf, cell->back(), up));
960                         InsetMathScript * p = cell->back().nucleus()->asScriptInset();
961                         // special handling of {}-bases
962                         // Here we could remove the brace inset for things
963                         // like {a'}^2 and add the braces back in
964                         // InsetMathScript::write().
965                         // We do not do it, since it is not possible to detect
966                         // reliably whether the braces are needed because the
967                         // nucleus contains more than one symbol, or whether
968                         // they are needed for unknown commands like \xx{a}_0
969                         // or \yy{a}{b}_0. This was done in revision 14819
970                         // in an unreliable way. See this thread
971                         // http://www.mail-archive.com/lyx-devel%40lists.lyx.org/msg104917.html
972                         // for more details.
973                         // However, we remove empty braces because they look
974                         // ugly on screen and we are sure that they were added
975                         // by the write() method (and will be re-added on save).
976                         if (p->nuc().size() == 1 &&
977                             p->nuc().back()->asBraceInset() &&
978                             p->nuc().back()->asBraceInset()->cell(0).empty())
979                                 p->nuc().erase(0);
980
981                         parse(p->cell(p->idxOfScript(up)), FLAG_ITEM, mode);
982                         if (limits) {
983                                 p->limits(limits);
984                                 limits = 0;
985                         }
986                 }
987
988                 else if (t.character() == ']' && (flags & FLAG_BRACK_LAST)) {
989                         //lyxerr << "finished reading option" << endl;
990                         return success_;
991                 }
992
993                 else if (t.cat() == catOther) {
994                         char_type c = t.character();
995                         if (isAsciiOrMathAlpha(c)
996                             || mode_ & Parse::VERBATIM
997                             || !(mode_ & Parse::USETEXT)
998                             || mode == InsetMath::TEXT_MODE) {
999                                 cell->push_back(MathAtom(new InsetMathChar(c)));
1000                         } else {
1001                                 MathAtom at = createInsetMath("text", buf);
1002                                 at.nucleus()->cell(0).push_back(MathAtom(new InsetMathChar(c)));
1003                                 while (nextToken().cat() == catOther
1004                                        && !isAsciiOrMathAlpha(nextToken().character())) {
1005                                         c = getToken().character();
1006                                         at.nucleus()->cell(0).push_back(MathAtom(new InsetMathChar(c)));
1007                                 }
1008                                 cell->push_back(at);
1009                         }
1010                 }
1011
1012                 else if (t.cat() == catComment) {
1013                         docstring s;
1014                         while (good()) {
1015                                 Token const & t = getToken();
1016                                 if (t.cat() == catNewline)
1017                                         break;
1018                                 s += t.asString();
1019                         }
1020                         cell->push_back(MathAtom(new InsetMathComment(buf, s)));
1021                         skipSpaces();
1022                 }
1023
1024                 //
1025                 // control sequences
1026                 //
1027
1028                 else if (t.cs() == "lyxlock") {
1029                         if (cell->size())
1030                                 cell->back().nucleus()->lock(true);
1031                 }
1032
1033                 else if ((t.cs() == "global" && nextToken().cs() == "def") ||
1034                          t.cs() == "def") {
1035                         if (t.cs() == "global")
1036                                 getToken();
1037                         
1038                         // get name
1039                         docstring name = getToken().cs();
1040                         
1041                         // read parameters
1042                         int nargs = 0;
1043                         docstring pars;
1044                         while (good() && nextToken().cat() != catBegin) {
1045                                 pars += getToken().cs();
1046                                 ++nargs;
1047                         }
1048                         nargs /= 2;
1049                         
1050                         // read definition
1051                         MathData def;
1052                         parse(def, FLAG_ITEM, InsetMath::UNDECIDED_MODE);
1053                         
1054                         // is a version for display attached?
1055                         skipSpaces();
1056                         MathData display;
1057                         if (nextToken().cat() == catBegin)
1058                                 parse(display, FLAG_ITEM, InsetMath::MATH_MODE);
1059                         
1060                         cell->push_back(MathAtom(new MathMacroTemplate(buf,
1061                                 name, nargs, 0, MacroTypeDef,
1062                                 vector<MathData>(), def, display)));
1063                 }
1064                 
1065                 else if (t.cs() == "newcommand" ||
1066                          t.cs() == "renewcommand" ||
1067                          t.cs() == "newlyxcommand") {
1068                         // get name
1069                         if (getToken().cat() != catBegin) {
1070                                 error("'{' in \\newcommand expected (1) ");
1071                                 return success_;
1072                         }
1073                         docstring name = getToken().cs();
1074                         if (getToken().cat() != catEnd) {
1075                                 error("'}' in \\newcommand expected");
1076                                 return success_;
1077                         }
1078                                 
1079                         // get arity
1080                         docstring const arg = getArg('[', ']');
1081                         int nargs = 0;
1082                         if (!arg.empty())
1083                                 nargs = convert<int>(arg);
1084                                 
1085                         // optional argument given?
1086                         skipSpaces();
1087                         int optionals = 0;
1088                         vector<MathData> optionalValues;
1089                         while (nextToken().character() == '[') {
1090                                 getToken();
1091                                 optionalValues.push_back(MathData());
1092                                 parse(optionalValues[optionals], FLAG_BRACK_LAST, mode);
1093                                 ++optionals;
1094                         }
1095                         
1096                         MathData def;
1097                         parse(def, FLAG_ITEM, InsetMath::UNDECIDED_MODE);
1098                         
1099                         // is a version for display attached?
1100                         skipSpaces();
1101                         MathData display;
1102                         if (nextToken().cat() == catBegin)
1103                                 parse(display, FLAG_ITEM, InsetMath::MATH_MODE);
1104                         
1105                         cell->push_back(MathAtom(new MathMacroTemplate(buf,
1106                                 name, nargs, optionals, MacroTypeNewcommand,
1107                                 optionalValues, def, display)));
1108                 }
1109                 
1110                 else if (t.cs() == "newcommandx" ||
1111                          t.cs() == "renewcommandx") {
1112                         // \newcommandx{\foo}[2][usedefault, addprefix=\global,1=default]{#1,#2}
1113                         // get name
1114                         docstring name;
1115                         if (nextToken().cat() == catBegin) {
1116                                 getToken();
1117                                 name = getToken().cs();
1118                                 if (getToken().cat() != catEnd) {
1119                                         error("'}' in \\newcommandx expected");
1120                                         return success_;
1121                                 }
1122                         } else
1123                                 name = getToken().cs();
1124                                 
1125                         // get arity
1126                         docstring const arg = getArg('[', ']');
1127                         if (arg.empty()) {
1128                                 error("[num] in \\newcommandx expected");
1129                                 return success_;
1130                         }
1131                         int nargs = convert<int>(arg);
1132                         
1133                         // get options
1134                         int optionals = 0;
1135                         vector<MathData> optionalValues;
1136                         if (nextToken().character() == '[') {
1137                                 // skip '['
1138                                 getToken();
1139                                         
1140                                 // handle 'opt=value' options, separated by ','.
1141                                 skipSpaces();
1142                                 while (nextToken().character() != ']' && good()) {
1143                                         if (nextToken().character() >= '1'
1144                                             && nextToken().character() <= '9') {
1145                                                 // optional value -> get parameter number
1146                                                 int n = getChar() - '0';
1147                                                 if (n > nargs) {
1148                                                         error("Arity of \\newcommandx too low "
1149                                                               "for given optional parameter.");
1150                                                         return success_;
1151                                                 }
1152                                                 
1153                                                 // skip '='
1154                                                 if (getToken().character() != '=') {
1155                                                         error("'=' and optional parameter value "
1156                                                               "expected for \\newcommandx");
1157                                                         return success_;
1158                                                 }
1159                                                 
1160                                                 // get value
1161                                                 int optNum = max(size_t(n), optionalValues.size());
1162                                                 optionalValues.resize(optNum);
1163                                                 optionalValues[n - 1].clear();
1164                                                 while (nextToken().character() != ']'
1165                                                        && nextToken().character() != ',') {
1166                                                         MathData data;
1167                                                         parse(data, FLAG_ITEM, InsetMath::UNDECIDED_MODE);
1168                                                         optionalValues[n - 1].append(data);
1169                                                 }
1170                                                 optionals = max(n, optionals);
1171                                         } else if (nextToken().cat() == catLetter) {
1172                                                 // we in fact ignore every non-optional
1173                                                 // parameter
1174                                                 
1175                                                 // get option name
1176                                                 docstring opt;
1177                                                 while (nextToken().cat() == catLetter)
1178                                                         opt += getChar();
1179                                         
1180                                                 // value?
1181                                                 skipSpaces();
1182                                                 MathData value;
1183                                                 if (nextToken().character() == '=') {
1184                                                         getToken();
1185                                                         while (nextToken().character() != ']'
1186                                                                 && nextToken().character() != ',')
1187                                                                 parse(value, FLAG_ITEM, 
1188                                                                       InsetMath::UNDECIDED_MODE);
1189                                                 }
1190                                         } else {
1191                                                 error("option for \\newcommandx expected");
1192                                                 return success_;
1193                                         }
1194                                         
1195                                         // skip komma
1196                                         skipSpaces();
1197                                         if (nextToken().character() == ',') {
1198                                                 getChar();
1199                                                 skipSpaces();
1200                                         } else if (nextToken().character() != ']') {
1201                                                 error("Expecting ',' or ']' in options "
1202                                                       "of \\newcommandx");
1203                                                 return success_;
1204                                         }
1205                                 }
1206                                 
1207                                 // skip ']'
1208                                 if (!good())
1209                                         return success_;
1210                                 getToken();
1211                         }
1212
1213                         // get definition
1214                         MathData def;
1215                         parse(def, FLAG_ITEM, InsetMath::UNDECIDED_MODE);
1216
1217                         // is a version for display attached?
1218                         skipSpaces();
1219                         MathData display;
1220                         if (nextToken().cat() == catBegin)
1221                                 parse(display, FLAG_ITEM, InsetMath::MATH_MODE);
1222
1223                         cell->push_back(MathAtom(new MathMacroTemplate(buf,
1224                                 name, nargs, optionals, MacroTypeNewcommandx,
1225                                 optionalValues, def, display)));
1226                 }
1227
1228                 else if (t.cs() == "(") {
1229                         cell->push_back(MathAtom(new InsetMathEnsureMath(buf)));
1230                         parse(cell->back().nucleus()->cell(0), FLAG_SIMPLE2, InsetMath::MATH_MODE);
1231                 }
1232
1233                 else if (t.cs() == "[") {
1234                         if (mode != InsetMath::UNDECIDED_MODE) {
1235                                 error("bad math environment");
1236                                 break;
1237                         }
1238                         cell->push_back(MathAtom(new InsetMathHull(buf, hullEquation)));
1239                         parse2(cell->back(), FLAG_EQUATION, InsetMath::MATH_MODE, false);
1240                 }
1241
1242                 else if (t.cs() == "protect")
1243                         // ignore \\protect, will hopefully be re-added during output
1244                         ;
1245
1246                 else if (t.cs() == "end") {
1247                         if (flags & FLAG_END) {
1248                                 // eat environment name
1249                                 docstring const name = getArg('{', '}');
1250                                 if (environments_.empty())
1251                                         error("'found \\end{" + name +
1252                                               "}' without matching '\\begin{" +
1253                                               name + "}'");
1254                                 else if (name != environments_.back())
1255                                         error("'\\end{" + name +
1256                                               "}' does not match '\\begin{" +
1257                                               environments_.back() + "}'");
1258                                 else {
1259                                         environments_.pop_back();
1260                                         // Delete empty last row in matrix
1261                                         // like insets.
1262                                         // If you abuse InsetMathGrid for
1263                                         // non-matrix like structures you
1264                                         // probably need to refine this test.
1265                                         // Right now we only have to test for
1266                                         // single line hull insets.
1267                                         if (grid.nrows() > 1 && innerHull(name))
1268                                                 delEmptyLastRow(grid);
1269                                         return success_;
1270                                 }
1271                         } else
1272                                 error("found 'end' unexpectedly");
1273                 }
1274
1275                 else if (t.cs() == ")") {
1276                         if (flags & FLAG_SIMPLE2)
1277                                 return success_;
1278                         error("found '\\)' unexpectedly");
1279                 }
1280
1281                 else if (t.cs() == "]") {
1282                         if (flags & FLAG_EQUATION)
1283                                 return success_;
1284                         error("found '\\]' unexpectedly");
1285                 }
1286
1287                 else if (t.cs() == "\\") {
1288                         if (flags & FLAG_ALIGN)
1289                                 return success_;
1290                         bool added = false;
1291                         if (nextToken().asInput() == "*") {
1292                                 getToken();
1293                                 added = addRow(grid, cellrow, docstring(), false);
1294                         } else if (good())
1295                                 added = addRow(grid, cellrow, getArg('[', ']'));
1296                         else
1297                                 error("missing token after \\\\");
1298                         if (added) {
1299                                 cellcol = 0;
1300                                 if (grid.asHullInset())
1301                                         grid.asHullInset()->numbered(
1302                                                         cellrow, numbered);
1303                                 cell = &grid.cell(grid.index(cellrow,
1304                                                              cellcol));
1305                         }
1306                 }
1307
1308 #if 0
1309                 else if (t.cs() == "multicolumn") {
1310                         // extract column count and insert dummy cells
1311                         MathData count;
1312                         parse(count, FLAG_ITEM, mode);
1313                         int cols = 1;
1314                         if (!extractNumber(count, cols)) {
1315                                 success_ = false;
1316                                 lyxerr << " can't extract number of cells from " << count << endl;
1317                         }
1318                         // resize the table if necessary
1319                         for (int i = 0; i < cols; ++i) {
1320                                 if (addCol(grid, cellcol)) {
1321                                         cell = &grid.cell(grid.index(
1322                                                         cellrow, cellcol));
1323                                         // mark this as dummy
1324                                         grid.cellinfo(grid.index(
1325                                                 cellrow, cellcol)).dummy_ = true;
1326                                 }
1327                         }
1328                         // the last cell is the real thing, not a dummy
1329                         grid.cellinfo(grid.index(cellrow, cellcol)).dummy_ = false;
1330
1331                         // read special alignment
1332                         MathData align;
1333                         parse(align, FLAG_ITEM, mode);
1334                         //grid.cellinfo(grid.index(cellrow, cellcol)).align_ = extractString(align);
1335
1336                         // parse the remaining contents into the "real" cell
1337                         parse(*cell, FLAG_ITEM, mode);
1338                 }
1339 #endif
1340
1341                 else if (t.cs() == "limits" || t.cs() == "nolimits") {
1342                         CatCode const cat = nextToken().cat();
1343                         if (cat == catSuper || cat == catSub)
1344                                 limits = t.cs() == "limits" ? 1 : -1;
1345                         else {
1346                                 MathAtom at = createInsetMath(t.cs(), buf);
1347                                 cell->push_back(at);
1348                         }
1349                 }
1350
1351                 else if (t.cs() == "nonumber") {
1352                         if (grid.asHullInset())
1353                                 grid.asHullInset()->numbered(cellrow, false);
1354                 }
1355
1356                 else if (t.cs() == "number") {
1357                         if (grid.asHullInset())
1358                                 grid.asHullInset()->numbered(cellrow, true);
1359                 }
1360
1361                 else if (t.cs() == "hline") {
1362                         grid.rowinfo(cellrow).lines_ ++;
1363                 }
1364
1365                 else if (t.cs() == "sqrt") {
1366                         MathData ar;
1367                         parse(ar, FLAG_OPTION, mode);
1368                         if (ar.size()) {
1369                                 cell->push_back(MathAtom(new InsetMathRoot(buf)));
1370                                 cell->back().nucleus()->cell(0) = ar;
1371                                 parse(cell->back().nucleus()->cell(1), FLAG_ITEM, mode);
1372                         } else {
1373                                 cell->push_back(MathAtom(new InsetMathSqrt(buf)));
1374                                 parse(cell->back().nucleus()->cell(0), FLAG_ITEM, mode);
1375                         }
1376                 }
1377
1378                 else if (t.cs() == "unit") {
1379                         // Allowed formats \unit[val]{unit}
1380                         MathData ar;
1381                         parse(ar, FLAG_OPTION, mode);
1382                         if (ar.size()) {
1383                                 cell->push_back(MathAtom(new InsetMathFrac(buf, InsetMathFrac::UNIT)));
1384                                 cell->back().nucleus()->cell(0) = ar;
1385                                 parse(cell->back().nucleus()->cell(1), FLAG_ITEM, mode);
1386                         } else {
1387                                 cell->push_back(MathAtom(new InsetMathFrac(buf, InsetMathFrac::UNIT, 1)));
1388                                 parse(cell->back().nucleus()->cell(0), FLAG_ITEM, mode);
1389                         }
1390                 }
1391
1392                 else if (t.cs() == "unitfrac") {
1393                         // Here allowed formats are \unitfrac[val]{num}{denom}
1394                         MathData ar;
1395                         parse(ar, FLAG_OPTION, mode);
1396                         if (ar.size()) {
1397                                 cell->push_back(MathAtom(new InsetMathFrac(buf, InsetMathFrac::UNITFRAC, 3)));
1398                                 cell->back().nucleus()->cell(2) = ar;
1399                         } else {
1400                                 cell->push_back(MathAtom(new InsetMathFrac(buf, InsetMathFrac::UNITFRAC)));
1401                         }
1402                         parse(cell->back().nucleus()->cell(0), FLAG_ITEM, mode);
1403                         parse(cell->back().nucleus()->cell(1), FLAG_ITEM, mode);
1404                 }
1405
1406                 else if (t.cs() == "cfrac") {
1407                         // allowed formats are \cfrac[pos]{num}{denom}
1408                         docstring const arg = getArg('[', ']');
1409                         //lyxerr << "got so far: '" << arg << "'" << endl;                              
1410                                 if (arg == "l")
1411                                         cell->push_back(MathAtom(new InsetMathFrac(buf, InsetMathFrac::CFRACLEFT)));
1412                                 else if (arg == "r")
1413                                         cell->push_back(MathAtom(new InsetMathFrac(buf, InsetMathFrac::CFRACRIGHT)));
1414                                 else if (arg.empty() || arg == "c")
1415                                         cell->push_back(MathAtom(new InsetMathFrac(buf, InsetMathFrac::CFRAC)));
1416                                 else {
1417                                         error("found invalid optional argument");
1418                                         break;
1419                                 }
1420                         parse(cell->back().nucleus()->cell(0), FLAG_ITEM, mode);
1421                         parse(cell->back().nucleus()->cell(1), FLAG_ITEM, mode);
1422                 }
1423
1424                 else if (t.cs() == "xrightarrow" || t.cs() == "xleftarrow") {
1425                         cell->push_back(createInsetMath(t.cs(), buf));
1426                         parse(cell->back().nucleus()->cell(1), FLAG_OPTION, mode);
1427                         parse(cell->back().nucleus()->cell(0), FLAG_ITEM, mode);
1428                 }
1429
1430                 else if (t.cs() == "ref" || t.cs() == "eqref" || t.cs() == "prettyref"
1431                           || t.cs() == "pageref" || t.cs() == "vpageref" || t.cs() == "vref") {
1432                         cell->push_back(MathAtom(new InsetMathRef(buf, t.cs())));
1433                         docstring const opt = parse_verbatim_option();
1434                         docstring const ref = parse_verbatim_item();
1435                         if (!opt.empty()) {
1436                                 cell->back().nucleus()->cell(1).push_back(
1437                                         MathAtom(new InsetMathString(opt)));
1438                         }
1439                         cell->back().nucleus()->cell(0).push_back(
1440                                         MathAtom(new InsetMathString(ref)));
1441                 }
1442
1443                 else if (t.cs() == "left") {
1444                         skipSpaces();
1445                         Token const & tl = getToken();
1446                         // \| and \Vert are equivalent, and InsetMathDelim
1447                         // can't handle \|
1448                         // FIXME: fix this in InsetMathDelim itself!
1449                         docstring const l = tl.cs() == "|" ? from_ascii("Vert") : tl.asString();
1450                         MathData ar;
1451                         parse(ar, FLAG_RIGHT, mode);
1452                         if (!good())
1453                                 break;
1454                         skipSpaces();
1455                         Token const & tr = getToken();
1456                         docstring const r = tr.cs() == "|" ? from_ascii("Vert") : tr.asString();
1457                         cell->push_back(MathAtom(new InsetMathDelim(buf, l, r, ar)));
1458                 }
1459
1460                 else if (t.cs() == "right") {
1461                         if (flags & FLAG_RIGHT)
1462                                 return success_;
1463                         //lyxerr << "got so far: '" << cell << "'" << endl;
1464                         error("Unmatched right delimiter");
1465                         return success_;
1466                 }
1467
1468                 else if (t.cs() == "begin") {
1469                         docstring const name = getArg('{', '}');
1470                         environments_.push_back(name);
1471
1472                         if (name == "array" || name == "subarray") {
1473                                 docstring const valign = parse_verbatim_option() + 'c';
1474                                 docstring const halign = parse_verbatim_item();
1475                                 cell->push_back(MathAtom(new InsetMathArray(buf, name,
1476                                         InsetMathGrid::guessColumns(halign), 1, (char)valign[0], halign)));
1477                                 parse2(cell->back(), FLAG_END, mode, false);
1478                         }
1479
1480                         else if (name == "tabular") {
1481                                 docstring const valign = parse_verbatim_option() + 'c';
1482                                 docstring const halign = parse_verbatim_item();
1483                                 cell->push_back(MathAtom(new InsetMathTabular(buf, name,
1484                                         InsetMathGrid::guessColumns(halign), 1, (char)valign[0], halign)));
1485                                 parse2(cell->back(), FLAG_END, InsetMath::TEXT_MODE, false);
1486                         }
1487
1488                         else if (name == "split" || name == "cases") {
1489                                 cell->push_back(createInsetMath(name, buf));
1490                                 parse2(cell->back(), FLAG_END, mode, false);
1491                         }
1492
1493                         else if (name == "alignedat") {
1494                                 docstring const valign = parse_verbatim_option() + 'c';
1495                                 // ignore this for a while
1496                                 getArg('{', '}');
1497                                 cell->push_back(MathAtom(new InsetMathSplit(buf, name, (char)valign[0])));
1498                                 parse2(cell->back(), FLAG_END, mode, false);
1499                         }
1500
1501                         else if (name == "math") {
1502                                 cell->push_back(MathAtom(new InsetMathEnsureMath(buf)));
1503                                 parse(cell->back().nucleus()->cell(0), FLAG_END, InsetMath::MATH_MODE);
1504                         }
1505
1506                         else if (name == "equation" || name == "equation*"
1507                                         || name == "displaymath") {
1508                                 if (mode != InsetMath::UNDECIDED_MODE) {
1509                                         error("bad math environment");
1510                                         break;
1511                                 }
1512                                 cell->push_back(MathAtom(new InsetMathHull(buf, hullEquation)));
1513                                 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, (name == "equation"));
1514                         }
1515
1516                         else if (name == "eqnarray" || name == "eqnarray*") {
1517                                 if (mode != InsetMath::UNDECIDED_MODE) {
1518                                         error("bad math environment");
1519                                         break;
1520                                 }
1521                                 cell->push_back(MathAtom(new InsetMathHull(buf, hullEqnArray)));
1522                                 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, !stared(name));
1523                         }
1524
1525                         else if (name == "align" || name == "align*") {
1526                                 if (mode != InsetMath::UNDECIDED_MODE) {
1527                                         error("bad math environment");
1528                                         break;
1529                                 }
1530                                 cell->push_back(MathAtom(new InsetMathHull(buf, hullAlign)));
1531                                 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, !stared(name));
1532                         }
1533
1534                         else if (name == "flalign" || name == "flalign*") {
1535                                 if (mode != InsetMath::UNDECIDED_MODE) {
1536                                         error("bad math environment");
1537                                         break;
1538                                 }
1539                                 cell->push_back(MathAtom(new InsetMathHull(buf, hullFlAlign)));
1540                                 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, !stared(name));
1541                         }
1542
1543                         else if (name == "alignat" || name == "alignat*") {
1544                                 if (mode != InsetMath::UNDECIDED_MODE) {
1545                                         error("bad math environment");
1546                                         break;
1547                                 }
1548                                 // ignore this for a while
1549                                 getArg('{', '}');
1550                                 cell->push_back(MathAtom(new InsetMathHull(buf, hullAlignAt)));
1551                                 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, !stared(name));
1552                         }
1553
1554                         else if (name == "xalignat" || name == "xalignat*") {
1555                                 if (mode != InsetMath::UNDECIDED_MODE) {
1556                                         error("bad math environment");
1557                                         break;
1558                                 }
1559                                 // ignore this for a while
1560                                 getArg('{', '}');
1561                                 cell->push_back(MathAtom(new InsetMathHull(buf, hullXAlignAt)));
1562                                 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, !stared(name));
1563                         }
1564
1565                         else if (name == "xxalignat") {
1566                                 if (mode != InsetMath::UNDECIDED_MODE) {
1567                                         error("bad math environment");
1568                                         break;
1569                                 }
1570                                 // ignore this for a while
1571                                 getArg('{', '}');
1572                                 cell->push_back(MathAtom(new InsetMathHull(buf, hullXXAlignAt)));
1573                                 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, !stared(name));
1574                         }
1575
1576                         else if (name == "multline" || name == "multline*") {
1577                                 if (mode != InsetMath::UNDECIDED_MODE) {
1578                                         error("bad math environment");
1579                                         break;
1580                                 }
1581                                 cell->push_back(MathAtom(new InsetMathHull(buf, hullMultline)));
1582                                 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, !stared(name));
1583                         }
1584
1585                         else if (name == "gather" || name == "gather*") {
1586                                 if (mode != InsetMath::UNDECIDED_MODE) {
1587                                         error("bad math environment");
1588                                         break;
1589                                 }
1590                                 cell->push_back(MathAtom(new InsetMathHull(buf, hullGather)));
1591                                 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, !stared(name));
1592                         }
1593
1594                         else if (latexkeys const * l = in_word_set(name)) {
1595                                 if (l->inset == "matrix") {
1596                                         cell->push_back(createInsetMath(name, buf));
1597                                         parse2(cell->back(), FLAG_END, mode, false);
1598                                 } else if (l->inset == "split") {
1599                                         docstring const valign = parse_verbatim_option() + 'c';
1600                                         cell->push_back(MathAtom(
1601                                                 new InsetMathSplit(buf, name, (char)valign[0])));
1602                                         parse2(cell->back(), FLAG_END, mode, false);
1603                                 } else {
1604                                         success_ = false;
1605                                         if (!(mode_ & Parse::QUIET)) {
1606                                                 dump();
1607                                                 lyxerr << "found math environment `"
1608                                                        << to_utf8(name)
1609                                                        << "' in symbols file with unsupported inset `"
1610                                                        << to_utf8(l->inset)
1611                                                        << "'." << endl;
1612                                         }
1613                                         // create generic environment inset
1614                                         cell->push_back(MathAtom(new InsetMathEnv(buf, name)));
1615                                         parse(cell->back().nucleus()->cell(0), FLAG_END, mode);
1616                                 }
1617                         }
1618
1619                         else {
1620                                 success_ = false;
1621                                 if (!(mode_ & Parse::QUIET)) {
1622                                         dump();
1623                                         lyxerr << "found unknown math environment '"
1624                                                << to_utf8(name) << "'" << endl;
1625                                 }
1626                                 // create generic environment inset
1627                                 cell->push_back(MathAtom(new InsetMathEnv(buf, name)));
1628                                 parse(cell->back().nucleus()->cell(0), FLAG_END, mode);
1629                         }
1630                 }
1631
1632                 else if (t.cs() == "kern") {
1633                         // FIXME: A hack...
1634                         docstring s;
1635                         int num_tokens = 0;
1636                         while (true) {
1637                                 Token const & t = getToken();
1638                                 ++num_tokens;
1639                                 if (!good()) {
1640                                         s.clear();
1641                                         while (num_tokens--)
1642                                                 putback();
1643                                         break;
1644                                 }
1645                                 s += t.character();
1646                                 if (isValidLength(to_utf8(s)))
1647                                         break;
1648                         }
1649                         if (s.empty())
1650                                 cell->push_back(MathAtom(new InsetMathKern));
1651                         else
1652                                 cell->push_back(MathAtom(new InsetMathKern(s)));
1653                 }
1654
1655                 else if (t.cs() == "label") {
1656                         // FIXME: This is swallowed in inline formulas
1657                         docstring label = parse_verbatim_item();
1658                         MathData ar;
1659                         asArray(label, ar);
1660                         if (grid.asHullInset()) {
1661                                 grid.asHullInset()->label(cellrow, label);
1662                         } else {
1663                                 cell->push_back(createInsetMath(t.cs(), buf));
1664                                 cell->push_back(MathAtom(new InsetMathBrace(ar)));
1665                         }
1666                 }
1667
1668                 else if (t.cs() == "choose" || t.cs() == "over"
1669                                 || t.cs() == "atop" || t.cs() == "brace"
1670                                 || t.cs() == "brack") {
1671                         MathAtom at = createInsetMath(t.cs(), buf);
1672                         at.nucleus()->cell(0) = *cell;
1673                         cell->clear();
1674                         parse(at.nucleus()->cell(1), flags, mode);
1675                         cell->push_back(at);
1676                         return success_;
1677                 }
1678
1679                 else if (t.cs() == "color") {
1680                         docstring const color = parse_verbatim_item();
1681                         cell->push_back(MathAtom(new InsetMathColor(buf, true, color)));
1682                         parse(cell->back().nucleus()->cell(0), flags, mode);
1683                         return success_;
1684                 }
1685
1686                 else if (t.cs() == "textcolor") {
1687                         docstring const color = parse_verbatim_item();
1688                         cell->push_back(MathAtom(new InsetMathColor(buf, false, color)));
1689                         parse(cell->back().nucleus()->cell(0), FLAG_ITEM, InsetMath::TEXT_MODE);
1690                 }
1691
1692                 else if (t.cs() == "normalcolor") {
1693                         cell->push_back(createInsetMath(t.cs(), buf));
1694                         parse(cell->back().nucleus()->cell(0), flags, mode);
1695                         return success_;
1696                 }
1697
1698                 else if (t.cs() == "substack") {
1699                         cell->push_back(createInsetMath(t.cs(), buf));
1700                         parse2(cell->back(), FLAG_ITEM, mode, false);
1701                         // Delete empty last row if present
1702                         InsetMathGrid & subgrid =
1703                                 *(cell->back().nucleus()->asGridInset());
1704                         if (subgrid.nrows() > 1)
1705                                 delEmptyLastRow(subgrid);
1706                 }
1707
1708                 else if (t.cs() == "xymatrix") {
1709                         odocstringstream os;
1710                         while (good() && nextToken().cat() != catBegin)
1711                                 os << getToken().asInput();
1712                         cell->push_back(createInsetMath(t.cs() + os.str(), buf));
1713                         parse2(cell->back(), FLAG_ITEM, mode, false);
1714                         // Delete empty last row if present
1715                         InsetMathGrid & subgrid =
1716                                 *(cell->back().nucleus()->asGridInset());
1717                         if (subgrid.nrows() > 1)
1718                                 delEmptyLastRow(subgrid);
1719                 }
1720
1721                 else if (t.cs() == "Diagram") {
1722                         odocstringstream os;
1723                         while (good() && nextToken().cat() != catBegin)
1724                                 os << getToken().asInput();
1725                         cell->push_back(createInsetMath(t.cs() + os.str(), buf));
1726                         parse2(cell->back(), FLAG_ITEM, mode, false);
1727                 }
1728
1729                 else if (t.cs() == "framebox" || t.cs() == "makebox") {
1730                         cell->push_back(createInsetMath(t.cs(), buf));
1731                         parse(cell->back().nucleus()->cell(0), FLAG_OPTION, InsetMath::TEXT_MODE);
1732                         parse(cell->back().nucleus()->cell(1), FLAG_OPTION, InsetMath::TEXT_MODE);
1733                         parse(cell->back().nucleus()->cell(2), FLAG_ITEM, InsetMath::TEXT_MODE);
1734                 }
1735
1736                 else if (t.cs() == "tag") {
1737                         if (nextToken().character() == '*') {
1738                                 getToken();
1739                                 cell->push_back(createInsetMath(t.cs() + '*', buf));
1740                         } else
1741                                 cell->push_back(createInsetMath(t.cs(), buf));
1742                         parse(cell->back().nucleus()->cell(0), FLAG_ITEM, InsetMath::TEXT_MODE);
1743                 }
1744
1745                 else if (t.cs() == "hspace" && nextToken().character() != '*') {
1746                         docstring const name = t.cs();
1747                         docstring const arg = parse_verbatim_item();
1748                         Length length;
1749                         if (isValidLength(to_utf8(arg), &length))
1750                                 cell->push_back(MathAtom(new InsetMathSpace(length)));
1751                         else {
1752                                 // Since the Length class cannot use length variables
1753                                 // we must not create an InsetMathSpace.
1754                                 cell->push_back(MathAtom(new MathMacro(buf, name)));
1755                                 MathData ar;
1756                                 mathed_parse_cell(ar, '{' + arg + '}', mode_);
1757                                 cell->append(ar);
1758                         }
1759                 }
1760
1761 #if 0
1762                 else if (t.cs() == "infer") {
1763                         MathData ar;
1764                         parse(ar, FLAG_OPTION, mode);
1765                         cell->push_back(createInsetMath(t.cs(), buf));
1766                         parse2(cell->back(), FLAG_ITEM, mode, false);
1767                 }
1768
1769                 // Disabled
1770                 else if (1 && t.cs() == "ar") {
1771                         auto_ptr<InsetMathXYArrow> p(new InsetMathXYArrow);
1772                         // try to read target
1773                         parse(p->cell(0), FLAG_OTPTION, mode);
1774                         // try to read label
1775                         if (nextToken().cat() == catSuper || nextToken().cat() == catSub) {
1776                                 p->up_ = nextToken().cat() == catSuper;
1777                                 getToken();
1778                                 parse(p->cell(1), FLAG_ITEM, mode);
1779                                 //lyxerr << "read label: " << p->cell(1) << endl;
1780                         }
1781
1782                         cell->push_back(MathAtom(p.release()));
1783                         //lyxerr << "read cell: " << cell << endl;
1784                 }
1785 #endif
1786
1787                 else if (t.cs() == "lyxmathsym") {
1788                         skipSpaces();
1789                         if (getToken().cat() != catBegin) {
1790                                 error("'{' expected in \\" + t.cs());
1791                                 return success_;
1792                         }
1793                         int count = 0;
1794                         docstring cmd;
1795                         CatCode cat = nextToken().cat();
1796                         while (good() && (count || cat != catEnd)) {
1797                                 if (cat == catBegin)
1798                                         ++count;
1799                                 else if (cat == catEnd)
1800                                         --count;
1801                                 cmd += getToken().asInput();
1802                                 cat = nextToken().cat();
1803                         }
1804                         if (getToken().cat() != catEnd) {
1805                                 error("'}' expected in \\" + t.cs());
1806                                 return success_;
1807                         }
1808                         docstring rem;
1809                         do {
1810                                 cmd = Encodings::fromLaTeXCommand(cmd, rem);
1811                                 for (size_t i = 0; i < cmd.size(); ++i)
1812                                         cell->push_back(MathAtom(new InsetMathChar(cmd[i])));
1813                                 if (rem.size()) {
1814                                         char_type c = rem[0];
1815                                         cell->push_back(MathAtom(new InsetMathChar(c)));
1816                                         cmd = rem.substr(1);
1817                                         rem.clear();
1818                                 } else
1819                                         cmd.clear();
1820                         } while (cmd.size());
1821                 }
1822
1823                 else if (t.cs().size()) {
1824                         latexkeys const * l = in_word_set(t.cs());
1825
1826                         if (buf && (mode_ & Parse::TRACKMACRO) && l)
1827                                 buf->updateMacros();
1828
1829                         bool const is_user_macro =
1830                                 (buf && buf->getMacro(t.cs(), false) != 0);
1831
1832                         if (l && !is_user_macro) {
1833                                 if (l->inset == "big") {
1834                                         skipSpaces();
1835                                         docstring const delim = getToken().asInput();
1836                                         if (InsetMathBig::isBigInsetDelim(delim))
1837                                                 cell->push_back(MathAtom(
1838                                                         new InsetMathBig(t.cs(), delim)));
1839                                         else {
1840                                                 cell->push_back(createInsetMath(t.cs(), buf));
1841                                                 putback();
1842                                         }
1843                                 }
1844
1845                                 else if (l->inset == "font") {
1846                                         cell->push_back(createInsetMath(t.cs(), buf));
1847                                         parse(cell->back().nucleus()->cell(0),
1848                                                 FLAG_ITEM, asMode(mode, l->extra));
1849                                 }
1850
1851                                 else if (l->inset == "oldfont") {
1852                                         cell->push_back(createInsetMath(t.cs(), buf));
1853                                         parse(cell->back().nucleus()->cell(0),
1854                                                 flags | FLAG_ALIGN, asMode(mode, l->extra));
1855                                         if (prevToken().cat() != catAlign &&
1856                                             prevToken().cs() != "\\")
1857                                                 return success_;
1858                                         putback();
1859                                 }
1860
1861                                 else if (l->inset == "style") {
1862                                         cell->push_back(createInsetMath(t.cs(), buf));
1863                                         parse(cell->back().nucleus()->cell(0),
1864                                                 flags | FLAG_ALIGN, mode);
1865                                         if (prevToken().cat() != catAlign &&
1866                                             prevToken().cs() != "\\")
1867                                                 return success_;
1868                                         putback();
1869                                 }
1870
1871                                 else {
1872                                         MathAtom at = createInsetMath(t.cs(), buf);
1873                                         for (InsetMath::idx_type i = 0; i < at->nargs(); ++i)
1874                                                 parse(at.nucleus()->cell(i),
1875                                                         FLAG_ITEM, asMode(mode, l->extra));
1876                                         cell->push_back(at);
1877                                 }
1878                         }
1879
1880                         else {
1881                                 bool is_unicode_symbol = false;
1882                                 if (mode == InsetMath::TEXT_MODE && !is_user_macro) {
1883                                         int num_tokens = 0;
1884                                         docstring cmd = prevToken().asInput();
1885                                         CatCode cat = nextToken().cat();
1886                                         if (cat == catBegin) {
1887                                                 int count = 0;
1888                                                 while (good() && (count || cat != catEnd)) {
1889                                                         cat = nextToken().cat();
1890                                                         cmd += getToken().asInput();
1891                                                         ++num_tokens;
1892                                                         if (cat == catBegin)
1893                                                                 ++count;
1894                                                         else if (cat == catEnd)
1895                                                                 --count;
1896                                                 }
1897                                         }
1898                                         bool is_combining;
1899                                         char_type c =
1900                                                 Encodings::fromLaTeXCommand(cmd, is_combining);
1901                                         if (is_combining) {
1902                                                 if (cat == catLetter)
1903                                                         cmd += '{';
1904                                                 cmd += getToken().asInput();
1905                                                 ++num_tokens;
1906                                                 if (cat == catLetter)
1907                                                         cmd += '}';
1908                                                 c = Encodings::fromLaTeXCommand(cmd, is_combining);
1909                                         }
1910                                         if (c) {
1911                                                 is_unicode_symbol = true;
1912                                                 cell->push_back(MathAtom(new InsetMathChar(c)));
1913                                         } else {
1914                                                 while (num_tokens--)
1915                                                         putback();
1916                                         }
1917                                 }
1918                                 if (!is_unicode_symbol) {
1919                                         MathAtom at = is_user_macro ?
1920                                                 MathAtom(new MathMacro(buf, t.cs()))
1921                                                 : createInsetMath(t.cs(), buf);
1922                                         InsetMath::mode_type m = mode;
1923                                         //if (m == InsetMath::UNDECIDED_MODE)
1924                                         //lyxerr << "default creation: m1: " << m << endl;
1925                                         if (at->currentMode() != InsetMath::UNDECIDED_MODE)
1926                                                 m = at->currentMode();
1927                                         //lyxerr << "default creation: m2: " << m << endl;
1928                                         InsetMath::idx_type start = 0;
1929                                         // this fails on \bigg[...\bigg]
1930                                         //MathData opt;
1931                                         //parse(opt, FLAG_OPTION, InsetMath::VERBATIM_MODE);
1932                                         //if (opt.size()) {
1933                                         //      start = 1;
1934                                         //      at.nucleus()->cell(0) = opt;
1935                                         //}
1936                                         for (InsetMath::idx_type i = start; i < at->nargs(); ++i) {
1937                                                 parse(at.nucleus()->cell(i), FLAG_ITEM, m);
1938                                                 skipSpaces();
1939                                         }
1940                                         cell->push_back(at);
1941                                 }
1942                         }
1943                 }
1944
1945
1946                 if (flags & FLAG_LEAVE) {
1947                         flags &= ~FLAG_LEAVE;
1948                         break;
1949                 }
1950         }
1951         return success_;
1952 }
1953
1954
1955
1956 } // anonymous namespace
1957
1958
1959 bool mathed_parse_cell(MathData & ar, docstring const & str, Parse::flags f)
1960 {
1961         return Parser(str, f, ar.buffer()).parse(ar, 0, f & Parse::TEXTMODE ?
1962                                 InsetMath::TEXT_MODE : InsetMath::MATH_MODE);
1963 }
1964
1965
1966 bool mathed_parse_cell(MathData & ar, istream & is, Parse::flags f)
1967 {
1968         return Parser(is, f, ar.buffer()).parse(ar, 0, f & Parse::TEXTMODE ?
1969                                 InsetMath::TEXT_MODE : InsetMath::MATH_MODE);
1970 }
1971
1972
1973 bool mathed_parse_normal(Buffer * buf, MathAtom & t, docstring const & str,
1974                          Parse::flags f)
1975 {
1976         return Parser(str, f, buf).parse(t);
1977 }
1978
1979
1980 bool mathed_parse_normal(Buffer * buf, MathAtom & t, Lexer & lex,
1981                          Parse::flags f)
1982 {
1983         return Parser(lex, f, buf).parse(t);
1984 }
1985
1986
1987 bool mathed_parse_normal(InsetMathGrid & grid, docstring const & str,
1988                          Parse::flags f)
1989 {
1990         return Parser(str, f, &grid.buffer()).parse1(grid, 0, f & Parse::TEXTMODE ?
1991                         InsetMath::TEXT_MODE : InsetMath::MATH_MODE, false);
1992 }
1993
1994
1995 void initParser()
1996 {
1997         fill(theCatcode, theCatcode + 128, catOther);
1998         fill(theCatcode + 'a', theCatcode + 'z' + 1, catLetter);
1999         fill(theCatcode + 'A', theCatcode + 'Z' + 1, catLetter);
2000
2001         theCatcode[int('\\')] = catEscape;
2002         theCatcode[int('{')]  = catBegin;
2003         theCatcode[int('}')]  = catEnd;
2004         theCatcode[int('$')]  = catMath;
2005         theCatcode[int('&')]  = catAlign;
2006         theCatcode[int('\n')] = catNewline;
2007         theCatcode[int('#')]  = catParameter;
2008         theCatcode[int('^')]  = catSuper;
2009         theCatcode[int('_')]  = catSub;
2010         theCatcode[int(0x7f)] = catIgnore;
2011         theCatcode[int(' ')]  = catSpace;
2012         theCatcode[int('\t')] = catSpace;
2013         theCatcode[int('\r')] = catNewline;
2014         theCatcode[int('~')]  = catActive;
2015         theCatcode[int('%')]  = catComment;
2016 }
2017
2018
2019 } // namespace lyx