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