]> git.lyx.org Git - features.git/blob - src/mathed/math_parser.C
Use references instead of pointers where possible
[features.git] / src / mathed / math_parser.C
1 /*
2  *  File:        math_parser.C
3  *  Purpose:     Parser for mathed
4  *  Author:      Alejandro Aguilar Sierra <asierra@servidor.unam.mx> 
5  *  Created:     January 1996
6  *  Description: Parse LaTeX2e math mode code.
7  *
8  *  Dependencies: Xlib, XForms
9  *
10  *  Copyright: 1996, Alejandro Aguilar Sierra
11  *
12  *   Version: 0.8beta.
13  *
14  *   You are free to use and modify this code under the terms of
15  *   the GNU General Public Licence version 2 or later.
16  */
17
18 #include <config.h>
19
20 #include <cctype>
21
22 #ifdef __GNUG__
23 #pragma implementation
24 #endif
25
26 #include "math_parser.h"
27 #include "array.h"
28 #include "math_inset.h"
29 #include "math_arrayinset.h"
30 #include "math_charinset.h"
31 #include "math_deliminset.h"
32 #include "math_factory.h"
33 #include "math_funcinset.h"
34 #include "math_kerninset.h"
35 #include "math_macro.h"
36 #include "math_macrotable.h"
37 #include "math_macrotemplate.h"
38 #include "math_matrixinset.h"
39 #include "math_rootinset.h"
40 #include "math_sqrtinset.h"
41 #include "math_scriptinset.h"
42 #include "math_specialcharinset.h"
43 #include "math_splitinset.h"
44 #include "math_sqrtinset.h"
45 #include "debug.h"
46 #include "support.h"
47 #include "lyxlex.h"
48 #include "support/lstrings.h"
49
50 using std::istream;
51 using std::ostream;
52 using std::ios;
53 using std::endl;
54
55
56 namespace {
57
58 bool stared(string const & s)
59 {
60         unsigned n = s.size();
61         return n && s[n - 1] == '*';
62 }
63
64
65 void add(MathArray & ar, char c, MathTextCodes code)
66 {
67         ar.push_back(MathAtom(new MathCharInset(c, code)));
68 }
69
70
71 // These are TeX's catcodes
72 enum CatCode {
73         catEscape,     // 0    backslash 
74         catBegin,      // 1    {
75         catEnd,        // 2    }
76         catMath,       // 3    $
77         catAlign,      // 4    &
78         catNewline,    // 5    ^^M
79         catParameter,  // 6    #
80         catSuper,      // 7    ^
81         catSub,        // 8    _
82         catIgnore,     // 9       
83         catSpace,      // 10   space
84         catLetter,     // 11   a-zA-Z
85         catOther,      // 12   none of the above
86         catActive,     // 13   ~
87         catComment,    // 14   %
88         catInvalid     // 15   <delete>
89 };
90
91 CatCode theCatcode[256];  
92
93
94 inline CatCode catcode(unsigned char c)
95 {
96         return theCatcode[c];
97 }
98
99
100 enum {
101         FLAG_BRACE      = 1 << 0,  //  an opening brace needed
102         FLAG_BRACE_LAST = 1 << 1,  //  last closing brace ends the parsing process
103         FLAG_RIGHT      = 1 << 2,  //  next \\right ends the parsing process
104         FLAG_END        = 1 << 3,  //  next \\end ends the parsing process
105         FLAG_BRACK_END  = 1 << 4,  //  next closing bracket ends the parsing process
106         FLAG_NEWLINE    = 1 << 6,  //  next \\\\ ends the parsing process
107         FLAG_ITEM       = 1 << 7,  //  read a (possibly braced token)
108         FLAG_BLOCK      = 1 << 8,  //  next block ends the parsing process
109         FLAG_LEAVE      = 1 << 9   //  leave the loop at the end
110 };
111
112
113 void catInit()
114 {
115         for (int i = 0; i <= 255; ++i) 
116                 theCatcode[i] = catOther;
117         for (int i = 'a'; i <= 'z'; ++i) 
118                 theCatcode[i] = catLetter;
119         for (int i = 'A'; i <= 'Z'; ++i) 
120                 theCatcode[i] = catLetter;
121
122         theCatcode['\\'] = catEscape;   
123         theCatcode['{']  = catBegin;    
124         theCatcode['}']  = catEnd;      
125         theCatcode['$']  = catMath;     
126         theCatcode['&']  = catAlign;    
127         theCatcode['\n'] = catNewline;  
128         theCatcode['#']  = catParameter;        
129         theCatcode['^']  = catSuper;    
130         theCatcode['_']  = catSub;      
131         theCatcode['\7f'] = catIgnore;    
132         theCatcode[' ']  = catSpace;    
133         theCatcode['\t'] = catSpace;    
134         theCatcode['\r'] = catSpace;    
135         theCatcode['~']  = catActive;   
136         theCatcode['%']  = catComment;  
137 }
138
139
140
141 //
142 // Helper class for parsing
143 //
144
145 class Token {
146 public:
147         ///
148         Token() : cs_(), char_(0), cat_(catIgnore) {}
149         ///
150         Token(char c, CatCode cat) : cs_(), char_(c), cat_(cat) {}
151         ///
152         Token(const string & cs) : cs_(cs), char_(0), cat_(catIgnore) {}
153
154         ///
155         string const & cs() const { return cs_; }
156         ///
157         CatCode cat() const { return cat_; }
158         ///
159         char character() const { return char_; }
160         ///
161         string asString() const;
162
163 private:        
164         ///
165         string cs_;
166         ///
167         char char_;
168         ///
169         CatCode cat_;
170 };
171
172 string Token::asString() const
173 {
174         return cs_.size() ? cs_ : string(1, char_);
175 }
176
177 bool operator==(Token const & s, Token const & t)
178 {
179         return s.character() == t.character()
180                 && s.cat() == t.cat() && s.cs() == t.cs(); 
181 }
182
183 bool operator!=(Token const & s, Token const & t)
184 {
185         return !(s == t);
186 }
187
188 ostream & operator<<(ostream & os, Token const & t)
189 {
190         if (t.cs().size())
191                 os << "\\" << t.cs();
192         else
193                 os << "[" << t.character() << "," << t.cat() << "]";
194         return os;
195 }
196
197
198 class Parser {
199
200 public:
201         ///
202         Parser(LyXLex & lex);
203         ///
204         Parser(istream & is);
205
206         ///
207         string parse_macro();
208         ///
209         bool parse_normal(MathAtom &);
210         ///
211         void parse_into(MathArray & array, unsigned flags, MathTextCodes = LM_TC_MIN);
212         ///
213         int lineno() const { return lineno_; }
214         ///
215         void putback();
216
217 private:
218         ///
219         string getArg(char lf, char rf);
220         ///
221         char getChar();
222         ///
223         void error(string const & msg);
224         ///
225         bool parse_lines(MathAtom & t, bool numbered, bool outmost);
226
227 private:
228         ///
229         void tokenize(istream & is);
230         ///
231         void tokenize(string const & s);
232         ///
233         void push_back(Token const & t);
234         ///
235         void pop_back();
236         ///
237         Token const & prevToken() const;
238         ///
239         Token const & nextToken() const;
240         ///
241         Token const & getToken();
242         ///
243         void lex(string const & s);
244         ///
245         bool good() const;
246
247         ///
248         int lineno_;
249         ///
250         std::vector<Token> tokens_;
251         ///
252         unsigned pos_;
253         ///
254         bool   curr_num_;
255         ///
256         string curr_label_;
257         ///
258         string curr_skip_;
259 };
260
261
262 Parser::Parser(LyXLex & lexer)
263         : lineno_(lexer.getLineNo()), pos_(0), curr_num_(false)
264 {
265         tokenize(lexer.getStream());
266         lexer.eatLine();
267 }
268
269
270 Parser::Parser(istream & is)
271         : lineno_(0), pos_(0), curr_num_(false)
272 {
273         tokenize(is);
274 }
275
276
277 void Parser::push_back(Token const & t)
278 {
279         tokens_.push_back(t);
280 }
281
282
283 void Parser::pop_back()
284 {
285         tokens_.pop_back();
286 }
287
288
289 Token const & Parser::prevToken() const
290 {
291         static const Token dummy;
292         return pos_ > 0 ? tokens_[pos_ - 1] : dummy;
293 }
294
295
296 Token const & Parser::nextToken() const
297 {
298         static const Token dummy;
299         return good() ? tokens_[pos_] : dummy;
300 }
301
302
303 Token const & Parser::getToken()
304 {
305         static const Token dummy;
306         return good() ? tokens_[pos_++] : dummy;
307 }
308
309
310 void Parser::putback()
311 {
312         --pos_;
313 }
314
315
316 bool Parser::good() const
317 {
318         return pos_ < tokens_.size();
319 }
320
321
322 char Parser::getChar()
323 {
324         if (!good())
325                 lyxerr << "The input stream is not well..." << endl;
326         return tokens_[pos_++].character();
327 }
328
329
330 string Parser::getArg(char lf, char rg)
331 {
332         string result;
333         char c = getChar();
334
335         if (c != lf)  
336                 putback();
337         else 
338                 while ((c = getChar()) != rg && good())
339                         result += c;
340
341         return result;
342 }
343
344
345 void Parser::tokenize(istream & is)
346 {
347         // eat everything up to the next \end_inset or end of stream
348         // and store it in s for further tokenization
349         string s;
350         char c;
351         while (is.get(c)) {
352                 s += c;
353                 if (s.size() >= 10 && s.substr(s.size() - 10) == "\\end_inset") {
354                         s = s.substr(0, s.size() - 10);
355                         break;
356                 }
357         }
358
359         // tokenize buffer
360         tokenize(s);
361 }
362
363
364 void Parser::tokenize(string const & buffer)
365 {
366         static bool init_done = false;
367         
368         if (!init_done) {
369                 catInit();
370                 init_done = true;
371         }
372
373         istringstream is(buffer.c_str(), ios::in | ios::binary);
374
375         char c;
376         while (is.get(c)) {
377
378                 switch (catcode(c)) {
379                         case catNewline: {
380                                 ++lineno_; 
381                                 is.get(c);
382                                 if (catcode(c) == catNewline)
383                                         ; //push_back(Token("par"));
384                                 else {
385                                         push_back(Token(' ', catSpace));
386                                         is.putback(c);  
387                                 }
388                                 break;
389                         }
390
391                         case catComment: {
392                                 while (is.get(c) && catcode(c) != catNewline)
393                                         ;
394                                 ++lineno_; 
395                                 break;
396                         }
397
398                         case catEscape: {
399                                 is.get(c);
400                                 string s(1, c);
401                                 if (catcode(c) == catLetter) {
402                                         while (is.get(c) && catcode(c) == catLetter)
403                                                 s += c;
404                                         if (catcode(c) == catSpace)
405                                                 while (is.get(c) && catcode(c) == catSpace)
406                                                         ;
407                                         is.putback(c);
408                                 }       
409                                 push_back(Token(s));
410                                 break;
411                         }
412
413                         default:
414                                 push_back(Token(c, catcode(c)));
415                 }
416         }
417
418 #if 0
419         lyxerr << "\nTokens: ";
420         for (unsigned i = 0; i < tokens_.size(); ++i)
421                 lyxerr << tokens_[i];
422         lyxerr << "\n";
423 #endif
424 }
425
426
427 void Parser::error(string const & msg) 
428 {
429         lyxerr << "Line ~" << lineno_ << ": Math parse error: " << msg << endl;
430         //exit(1);
431 }
432
433
434 bool Parser::parse_lines(MathAtom & t, bool numbered, bool outmost)
435 {       
436         MathGridInset * p = t->asGridInset();
437         if (!p) {
438                 lyxerr << "error in Parser::parse_lines() 1\n";
439                 return false;
440         }
441
442         const int cols = p->ncols();
443
444         // save global variables
445         bool   const saved_num   = curr_num_;
446         string const saved_label = curr_label_;
447
448         for (int row = 0; true; ++row) {
449                 // reset global variables
450                 curr_num_   = numbered;
451                 curr_label_.erase();
452
453                 // reading a row
454                 for (int col = 0; col < cols; ++col) {
455                         //lyxerr << "reading cell " << row << " " << col << "\n";
456                         parse_into(p->cell(col + row * cols), FLAG_BLOCK);
457
458                         // no ampersand
459                         if (prevToken().cat() != catAlign) {
460                                 //lyxerr << "less cells read than normal in row/col: "
461                                 //      << row << " " << col << "\n";
462                                 break;
463                         }
464                 }
465
466                 if (outmost) {
467                         MathMatrixInset * m = t->asMatrixInset();
468                         if (!m) {
469                                 lyxerr << "error in Parser::parse_lines() 2\n";
470                                 return false;
471                         }
472                         m->numbered(row, curr_num_);
473                         m->label(row, curr_label_);
474                         if (curr_skip_.size()) {
475                                 m->vskip(LyXLength(curr_skip_), row);
476                                 curr_skip_.erase();
477                         }
478                 }
479
480                 // no newline?
481                 if (prevToken() != Token("\\")) {
482                         //lyxerr << "no newline here\n";
483                         break;
484                 }
485
486                 p->appendRow();
487         }
488
489         // restore "global" variables
490         curr_num_   = saved_num;
491         curr_label_ = saved_label;
492
493         return true;
494 }
495
496
497 string Parser::parse_macro()
498 {
499         string name = "{error}";
500
501         while (nextToken().cat() == catSpace)
502                 getToken();
503
504         if (getToken().cs() != "newcommand") {
505                 lyxerr << "\\newcommand expected\n";
506                 return name;
507         }
508
509         if (getToken().cat() != catBegin) {
510                 lyxerr << "'{' expected\n";
511                 return name;
512         }
513
514         name = getToken().cs();
515
516         if (getToken().cat() != catEnd) {
517                 lyxerr << "'}' expected\n";
518                 return name;
519         }
520
521         string    arg  = getArg('[', ']');
522         int       narg = arg.empty() ? 0 : atoi(arg.c_str()); 
523         MathArray ar;
524         parse_into(ar, FLAG_BRACE | FLAG_BRACE_LAST);
525         MathMacroTable::create(name, narg, ar);
526         
527         return name;
528 }
529
530
531 bool Parser::parse_normal(MathAtom & matrix)
532 {
533         while (nextToken().cat() == catSpace)
534                 getToken();
535
536         Token const & t = getToken();
537
538         if (t.cat() == catMath || t.cs() == "(") {
539                 matrix = MathAtom(new MathMatrixInset(LM_OT_SIMPLE));
540                 parse_into(matrix->cell(0), 0);
541                 return true;
542         }
543
544         if (!t.cs().size()) {
545                 lyxerr << "start of math expected, got '" << t << "'\n";
546                 return false;
547         }
548
549         string const & cs = t.cs();
550
551         if (cs == "[") {
552                 curr_num_ = 0;
553                 curr_label_.erase();
554                 matrix = MathAtom(new MathMatrixInset(LM_OT_EQUATION));
555                 MathMatrixInset * p = matrix->asMatrixInset();
556                 parse_into(p->cell(0), 0);
557                 p->numbered(0, curr_num_);
558                 p->label(0, curr_label_);
559                 return p;
560         }
561
562         if (cs != "begin") {
563                 lyxerr << "'begin' of un-simple math expected, got '" << cs << "'\n";
564                 return false;
565         }
566
567         string const name = getArg('{', '}');
568
569         if (name == "equation" || name == "equation*") {
570                 curr_num_ = !stared(name);
571                 curr_label_.erase();
572                 matrix = MathAtom(new MathMatrixInset(LM_OT_EQUATION));
573                 MathMatrixInset * p = matrix->asMatrixInset();
574                 parse_into(p->cell(0), FLAG_END);
575                 p->numbered(0, curr_num_);
576                 p->label(0, curr_label_);
577                 return true;
578         }
579
580         if (name == "eqnarray" || name == "eqnarray*") {
581                 matrix = MathAtom(new MathMatrixInset(LM_OT_EQNARRAY));
582                 return parse_lines(matrix, !stared(name), true);
583         }
584
585         if (name == "align" || name == "align*") {
586                 matrix = MathAtom(new MathMatrixInset(LM_OT_ALIGN));
587                 return parse_lines(matrix, !stared(name), true);
588         }
589
590         if (name == "alignat" || name == "alignat*") {
591                 int nc = 2 * atoi(getArg('{', '}').c_str());
592                 matrix = MathAtom(new MathMatrixInset(LM_OT_ALIGNAT, nc));
593                 return parse_lines(matrix, !stared(name), true);
594         }
595
596         if (name == "xalignat" || name == "xalignat*") {
597                 int nc = 2 * atoi(getArg('{', '}').c_str());
598                 matrix = MathAtom(new MathMatrixInset(LM_OT_XALIGNAT, nc));
599                 return parse_lines(matrix, !stared(name), true);
600         }
601
602         if (name == "xxalignat") {
603                 int nc = 2 * atoi(getArg('{', '}').c_str());
604                 matrix = MathAtom(new MathMatrixInset(LM_OT_XXALIGNAT, nc));
605                 return parse_lines(matrix, !stared(name), true);
606         }
607
608         if (name == "multline" || name == "multline*") {
609                 matrix = MathAtom(new MathMatrixInset(LM_OT_MULTLINE));
610                 return parse_lines(matrix, !stared(name), true);
611         }
612
613         if (name == "gather" || name == "gather*") {
614                 matrix = MathAtom(new MathMatrixInset(LM_OT_GATHER));
615                 return parse_lines(matrix, !stared(name), true);
616         }
617
618         lyxerr[Debug::MATHED] << "1: unknown math environment: " << name << "\n";
619         return false;
620 }
621
622
623 void Parser::parse_into(MathArray & array, unsigned flags, MathTextCodes code)
624 {
625         MathTextCodes yyvarcode = LM_TC_MIN;
626
627         bool panic  = false;
628         int  limits = 0;
629
630         while (good()) {
631                 Token const & t = getToken();
632         
633                 //lyxerr << "t: " << t << " flags: " << flags << "'\n";
634                 //array.dump(lyxerr);
635                 //lyxerr << "\n";
636
637                 if (flags & FLAG_ITEM) {
638                         flags &= ~FLAG_ITEM;
639                         if (t.cat() == catBegin) { 
640                                 // skip the brace and collect everything to the next matching
641                                 // closing brace
642                                 flags |= FLAG_BRACE_LAST;
643                                 continue;
644                         } else {
645                                 // handle only this single token, leave the loop if done
646                                 flags |= FLAG_LEAVE;
647                         }
648                 }
649
650                 if (flags & FLAG_BRACE) {
651                         if (t.cat() != catBegin) {
652                                 error("Expected {. Maybe you forgot to enclose an argument in {}");
653                                 panic = true;
654                                 break;
655                         } else {
656                                 flags &= ~FLAG_BRACE;
657                                 continue;
658                         }
659                 }
660
661                 if (flags & FLAG_BLOCK) {
662                         if (t.cat() == catAlign || t.cs() == "\\")
663                                 return;
664                         if (t.cs() == "end") {
665                                 getArg('{', '}');
666                                 return;
667                         }
668                 }
669
670                 //
671                 // cat codes
672                 //
673                 if (t.cat() == catMath)
674                         break;
675
676                 else if (t.cat() == catLetter)
677                         add(array, t.character(), yyvarcode);
678
679                 else if (t.cat() == catSpace &&
680                                 (yyvarcode == LM_TC_TEXTRM || code == LM_TC_TEXTRM))
681                         add(array, ' ', yyvarcode);
682
683                 else if (t.cat() == catParameter) {
684                         Token const & n = getToken();
685                         array.push_back(MathAtom(new MathMacroArgument(n.character() - '0')));
686                 }
687
688                 else if (t.cat() == catBegin) {
689                         add(array, '{', LM_TC_TEX);
690                 }
691
692                 else if (t.cat() == catEnd) {
693                         if (flags & FLAG_BRACE_LAST)
694                                 return;
695                         add(array, '}', LM_TC_TEX);
696                 }
697                 
698                 else if (t.cat() == catAlign) {
699                         lyxerr << "found tab unexpectedly, array: '" << array << "'\n";
700                         add(array, '&', LM_TC_TEX);
701                 }
702                 
703                 else if (t.cat() == catSuper || t.cat() == catSub) {
704                         bool up = (t.cat() == catSuper);
705                         MathScriptInset * p = 0; 
706                         if (array.size()) 
707                                 p = array.back()->asScriptInset();
708                         if (!p || p->has(up)) {
709                                 array.push_back(MathAtom(new MathScriptInset(up)));
710                                 p = array.back()->asScriptInset();
711                         }
712                         p->ensure(up);
713                         parse_into(p->cell(up), FLAG_ITEM);
714                         p->limits(limits);
715                         limits = 0;
716                 }
717
718                 else if (t.character() == ']' && (flags & FLAG_BRACK_END))
719                         return;
720
721                 else if (t.cat() == catOther)
722                         add(array, t.character(), yyvarcode);
723                 
724                 //
725                 // codesequences
726                 //      
727                 else if (t.cs() == "protect") 
728                         ;
729
730                 else if (t.cs() == "end")
731                         break;
732
733                 else if (t.cs() == ")")
734                         break;
735
736                 else if (t.cs() == "]")
737                         break;
738
739                 else if (t.cs() == "\\") {
740                         curr_skip_ = getArg('[', ']');
741                         if (flags & FLAG_NEWLINE)
742                                 return;
743                         lyxerr[Debug::MATHED]
744                                         << "found newline unexpectedly, array: '" << array << "'\n";
745                         array.push_back(createMathInset("\\"));
746                 }
747         
748                 else if (t.cs() == "limits")
749                         limits = 1;
750                 
751                 else if (t.cs() == "nolimits")
752                         limits = -1;
753                 
754                 else if (t.cs() == "nonumber")
755                         curr_num_ = false;
756
757                 else if (t.cs() == "number")
758                         curr_num_ = true;
759
760                 else if (t.cs() == "sqrt") {
761                         char c = getChar();
762                         if (c == '[') {
763                                 array.push_back(MathAtom(new MathRootInset));
764                                 parse_into(array.back()->cell(0), FLAG_BRACK_END);
765                                 parse_into(array.back()->cell(1), FLAG_ITEM);
766                         } else {
767                                 putback();
768                                 array.push_back(MathAtom(new MathSqrtInset));
769                                 parse_into(array.back()->cell(0), FLAG_ITEM);
770                         }
771                 }
772                 
773                 else if (t.cs() == "left") {
774                         string l = getToken().asString();
775                         MathArray ar;
776                         parse_into(ar, FLAG_RIGHT);
777                         string r = getToken().asString();
778                         MathAtom dl(new MathDelimInset(l, r));
779                         dl->cell(0) = ar;
780                         array.push_back(dl);
781                 }
782                 
783                 else if (t.cs() == "right") {
784                         if (!(flags & FLAG_RIGHT)) {
785                                 lyxerr << "got so far: '" << array << "'\n";
786                                 error("Unmatched right delimiter");
787                         }
788                         return;
789                 }
790
791 /*              
792                 case LM_TK_STY:
793                 {
794                         lyxerr[Debug::MATHED] << "LM_TK_STY not implemented\n";
795                         //MathArray tmp = array;
796                         //MathSizeInset * p = new MathSizeInset(MathStyles(lval_->id));
797                         //array.push_back(p);
798                         //parse_into(p->cell(0), FLAG_BRACE_FONT);
799                         break; 
800                 }
801
802 */
803                 
804                 else if (t.cs() == "begin") {
805                         string const name = getArg('{', '}');   
806                         if (name == "array") {
807                                 string const valign = getArg('[', ']') + 'c';
808                                 string const halign = getArg('{', '}');
809                                 array.push_back(
810                                         MathAtom(new MathArrayInset(halign.size(), 1, valign[0], halign)));
811                                 parse_lines(array.back(), false, false);
812                         } else if (name == "split") {
813                                 array.push_back(MathAtom(new MathSplitInset(1)));
814                                 parse_lines(array.back(), false, false);
815                         } else 
816                                 lyxerr[Debug::MATHED] << "unknow math inset begin '" << name << "'\n";  
817                 }
818         
819                 else if (t.cs() == "kern") {
820 #ifdef WITH_WARNINGS
821 #warning A hack...
822 #endif
823                         string s;
824                         while (1) {
825                                 Token const & t = getToken();
826                                 if (!good()) {
827                                         putback();      
828                                         break;
829                                 }
830                                 s += t.character();
831                                 if (isValidLength(s))
832                                         break;
833                         }
834                         array.push_back(MathAtom(new MathKernInset(s)));
835                 }
836
837                 else if (t.cs() == "label") {
838                         //MathArray ar;
839                         //parse_into(ar, FLAG_ITEM);
840                         //ostringstream os;
841                         //ar.write(os, true);
842                         //curr_label_ = os.str();
843                         // was: 
844                         curr_label_ = getArg('{', '}');
845                 }
846
847                 else if (t.cs() == "choose" || t.cs() == "over" || t.cs() == "atop") {
848                         MathAtom p = createMathInset(t.cs());
849                         // search backward for position of last '{' if any
850                         int pos;
851                         for (pos = array.size() - 1; pos >= 0; --pos)
852                                 if (array.at(pos)->getChar() == '{')
853                                         break;
854                         if (pos >= 0) {
855                                 // found it -> use the part after '{' as "numerator"
856                                 p->cell(0) = MathArray(array, pos + 1, array.size());
857                                 parse_into(p->cell(1), FLAG_BRACE_LAST);
858                                 // delete denominator and the '{'
859                                 array.erase(pos, array.size());
860                         } else if (flags & FLAG_RIGHT) {
861                                 // we are inside a \left ... \right block
862                                 //lyxerr << "found '" << t.cs() << "' enclosed by \\left .. \\right\n";
863                                 p->cell(0).swap(array);
864                                 parse_into(p->cell(1), FLAG_RIGHT);
865                                 // handle the right delimiter properly
866                                 putback();
867                         } else {
868                                 // not found -> use everything as "numerator"
869                                 p->cell(0).swap(array);
870                                 parse_into(p->cell(1), FLAG_BLOCK);
871                         }
872                         array.push_back(MathAtom(p));
873                 }
874         
875                 else if (t.cs().size()) {
876                         latexkeys const * l = in_word_set(t.cs());
877                         if (l) {
878                                 if (l->token == LM_TK_FONT) {
879                                         //lyxerr << "starting font\n";
880                                         //CatCode catSpaceSave = theCatcode[' '];
881                                         //if (l->id == LM_TC_TEXTRM) {
882                                         //      // temporarily change catcode   
883                                         //      theCatcode[' '] = catLetter;    
884                                         //}
885
886                                         MathTextCodes t = static_cast<MathTextCodes>(l->id);
887                                         MathArray ar;
888                                         parse_into(ar, FLAG_ITEM, t);
889                                         for (MathArray::iterator it = ar.begin(); it != ar.end(); ++it)
890                                                 (*it)->handleFont(t);
891                                         array.push_back(ar);
892
893                                         // undo catcode changes
894                                         ////theCatcode[' '] = catSpaceSave;
895                                         //lyxerr << "ending font\n";
896                                 }
897
898                                 else if (l->token == LM_TK_OLDFONT)
899                                         yyvarcode = static_cast<MathTextCodes>(l->id);
900
901                                 else {
902                                         MathAtom p = createMathInset(t.cs());
903                                         for (MathInset::idx_type i = 0; i < p->nargs(); ++i) 
904                                                 parse_into(p->cell(i), FLAG_ITEM);
905                                         array.push_back(p);
906                                 }
907                         }
908
909                         else {
910                                 MathAtom p = createMathInset(t.cs());
911                                 for (MathInset::idx_type i = 0; i < p->nargs(); ++i)
912                                         parse_into(p->cell(i), FLAG_ITEM);
913                                 array.push_back(p);
914                         }
915                 }
916
917
918                 if (flags & FLAG_LEAVE) {
919                         flags &= ~FLAG_LEAVE;
920                         break;
921                 }
922         }
923
924         if (panic) {
925                 lyxerr << " Math Panic, expect problems!\n";
926                 //   Search for the end command. 
927                 Token t;
928                 do {
929                         t = getToken();
930                 } while (good() && t.cs() != "end");
931         }
932 }
933
934
935
936 } // anonymous namespace
937
938
939
940 MathArray mathed_parse_cell(string const & str)
941 {
942         istringstream is(str.c_str());
943         Parser parser(is);
944         MathArray ar;
945         parser.parse_into(ar, 0);
946         return ar;
947 }
948
949
950
951 string mathed_parse_macro(string const & str)
952 {
953         istringstream is(str.c_str());
954         Parser parser(is);
955         return parser.parse_macro();
956 }
957
958 string mathed_parse_macro(istream & is)
959 {
960         Parser parser(is);
961         return parser.parse_macro();
962 }
963
964 string mathed_parse_macro(LyXLex & lex)
965 {
966         Parser parser(lex);
967         return parser.parse_macro();
968 }
969
970
971
972 bool mathed_parse_normal(MathAtom & t, string const & str)
973 {
974         istringstream is(str.c_str());
975         Parser parser(is);
976         return parser.parse_normal(t);
977 }
978
979 bool mathed_parse_normal(MathAtom & t, istream & is)
980 {
981         Parser parser(is);
982         return parser.parse_normal(t);
983 }
984
985 bool mathed_parse_normal(MathAtom & t, LyXLex & lex)
986 {
987         Parser parser(lex);
988         return parser.parse_normal(t);
989 }