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.
8 * Dependencies: Xlib, XForms
10 * Copyright: (c) 1996, Alejandro Aguilar Sierra
14 * You are free to use and modify this code under the terms of
15 * the GNU General Public Licence version 2 or later.
23 #pragma implementation "math_parser.h"
26 #include "math_parser.h"
27 #include "math_iter.h"
28 #include "math_inset.h"
29 #include "math_macro.h"
30 #include "math_root.h"
34 FLAG_BRACE = 1, // A { needed
35 FLAG_BRACE_ARG = 2, // Next { is argument
36 FLAG_BRACE_OPT = 4, // Optional {
37 FLAG_BRACE_LAST = 8, // Last } ends the parsing process
38 FLAG_BRACK_ARG = 16, // Optional [
39 FLAG_RIGHT = 32, // Next right ends the parsing process
40 FLAG_END = 64, // Next end ends the parsing process
41 FLAG_BRACE_FONT = 128, // Next } closes a font
42 FLAG_BRACK_END = 256 // Next ] ends the parsing process
48 static short mathed_env = LM_EN_INTEXT;
50 char * mathed_label = 0;
52 char const * latex_mathenv[] = {
62 char const * latex_mathspace[] = {
63 "!", ",", ":", ";", "quad", "qquad"
66 char const * latex_special_chars = "#$%&_{}";
68 // These are lexical codes, not semantic
74 LexBOP, // Binary operators or relations
86 static lexcode_enum lexcode[256];
87 static char yytext[256];
89 static istream * yyis;
90 static bool yy_mtextmode= false;
93 char * strnew(char const * s)
95 char * s1 = new char[strlen(s) + 1]; // this leaks when not delete[]'ed
101 static void mathPrintError(char const * msg)
103 lyxerr << "Line ~" << yylineno << ": Math parse error: "
108 static void LexInitCodes()
110 for (int i = 0; i <= 255; ++i) {
111 if (isalpha(i)) lexcode[i] = LexAlpha;
112 else if (isdigit(i)) lexcode[i] = LexDigit;
113 else if (isspace(i)) lexcode[i] = LexSpace;
114 else lexcode[i] = LexNone;
117 lexcode['\t'] = lexcode['\f'] = lexcode[' '] = LexSpace;
118 lexcode['\n'] = LexNewLine;
119 lexcode['%'] = LexComment;
120 lexcode['#'] = LexArgument;
121 lexcode['+'] = lexcode['-'] = lexcode['*'] = lexcode['/'] =
122 lexcode['<'] = lexcode['>'] = lexcode['='] = LexBOP;
124 lexcode['!'] = lexcode[','] = lexcode[':'] = lexcode[';'] = LexMathSpace;
125 lexcode['('] = lexcode[')'] = lexcode['|'] = lexcode['.'] = lexcode['?'] = LexOther;
126 lexcode['\'']= LexAlpha;
128 lexcode['['] = lexcode[']'] = lexcode['^'] = lexcode['_'] =
129 lexcode['&'] = LexSelf;
131 lexcode['\\'] = LexESC;
132 lexcode['{'] = LexOpen;
133 lexcode['}'] = LexClose;
137 static char LexGetArg(char lf, bool accept_spaces= false)
139 char rg, * p = &yytext[0];
142 while (yyis->good()) {
145 if (!lf) lf = c; else
147 lyxerr << "Math parse error: unexpected '"
152 rg = (lf == '{') ? '}': ((lf == '[') ? ']': ((lf == '(') ? ')': 0));
154 lyxerr << "Math parse error: unknown bracket '"
155 << lf << "'" << endl;
162 if ((c > ' ' || (c == ' ' && accept_spaces)) && bcnt>0) *(p++) = c;
163 } while (bcnt > 0 && yyis->good());
169 static int yylex(void)
171 static int init_done = 0;
174 if (!init_done) LexInitCodes();
176 while (yyis->good()) {
179 if (yy_mtextmode && c == ' ') {
184 if (lexcode[c] == LexNewLine) {
189 if (lexcode[c] == LexComment)
190 do yyis->get(c); while (c != '\n' % yyis->good()); // eat comments
192 if (lexcode[c] == LexDigit || lexcode[c] == LexOther || lexcode[c] == LexMathSpace)
193 { yylval.i= c; return LM_TK_STR; }
194 if (lexcode[c] == LexAlpha) { yylval.i= c; return LM_TK_ALPHA; }
195 if (lexcode[c] == LexBOP) { yylval.i= c; return LM_TK_BOP; }
196 if (lexcode[c] == LexSelf) { return c; }
197 if (lexcode[c] == LexArgument) {
200 return LM_TK_ARGUMENT;
202 if (lexcode[c] == LexOpen) { return LM_TK_OPEN; }
203 if (lexcode[c] == LexClose) { return LM_TK_CLOSE; }
205 if (lexcode[c] == LexESC) {
207 if (c == '\\') { return LM_TK_NEWLINE; }
208 if (c == '(') { yylval.i = LM_EN_INTEXT; return LM_TK_BEGIN; }
209 if (c == ')') { yylval.i = LM_EN_INTEXT; return LM_TK_END; }
210 if (c == '[') { yylval.i = LM_EN_DISPLAY; return LM_TK_BEGIN; }
211 if (c == ']') { yylval.i = LM_EN_DISPLAY; return LM_TK_END; }
212 if (strchr(latex_special_chars, c)) {
214 return LM_TK_SPECIAL;
216 if (lexcode[c] == LexMathSpace) {
218 for (i = 0; i < 4 && c != latex_mathspace[i][0]; ++i);
219 yylval.i = (i < 4) ? i: 0;
222 if (lexcode[c] == LexAlpha || lexcode[c] == LexDigit) {
223 char * p = &yytext[0];
224 while (lexcode[c] == LexAlpha || lexcode[c] == LexDigit) {
230 if (yyis->good()) yyis->putback(c);
231 latexkeys * l = in_word_set (yytext, strlen(yytext));
233 if (l->token == LM_TK_BEGIN || l->token == LM_TK_END) {
236 // for (i= 0; i<5 && strncmp(yytext, latex_mathenv[i],
237 // strlen(latex_mathenv[i])); i++);
239 for (i = 0; i < 6 && strcmp(yytext, latex_mathenv[i]); i++);
242 if (l->token == LM_TK_SPACE)
258 int parse_align(char * hor, char *)
261 for (char * c = hor; c && *c > ' '; ++c) ++nc;
266 // Accent hacks only for 0.12. Stolen from Cursor.
270 void setAccent(int ac)
272 if (ac > 0 && accent < 8) {
273 nestaccent[accent++] = ac;
275 accent = 0; // consumed!
279 MathedInset * doAccent(byte c, MathedTextCodes t)
281 MathedInset * ac = 0;
283 for (int i = accent - 1; i >= 0; --i) {
285 ac = new MathAccentInset(c, t, nestaccent[i]);
287 ac = new MathAccentInset(ac, nestaccent[i]);
289 accent = 0; // consumed!
295 MathedInset * doAccent(MathedInset * p)
297 MathedInset * ac = 0;
299 for (int i = accent - 1; i >= 0; --i) {
301 ac = new MathAccentInset(p, nestaccent[i]);
303 ac = new MathAccentInset(ac, nestaccent[i]);
305 accent = 0; // consumed!
311 LyxArrayBase * mathed_parse(unsigned flags, LyxArrayBase * array,
314 int t = yylex(), tprev = 0;
316 static int plevel = -1;
317 static int size = LM_ST_TEXT;
318 MathedTextCodes varcode = LM_TC_VAR;
319 MathedInset * binset = 0;
320 static MathMacroTemplate * macro= 0;
325 MathParInset * mt = (mtx) ? *mtx: 0;//(MathParInset*)0;
326 MathedRowSt * crow = (mt) ? mt->getRowSt() : 0;
329 if (!array) array = new LyxArrayBase;
330 MathedIter data(array);
332 if ((flags & FLAG_BRACE) && t != LM_TK_OPEN) {
333 if ((flags & FLAG_BRACK_ARG) && t == '[') {
336 mathPrintError("Expected {. Maybe you forgot to enclose an argument in {}");
341 MathedInsetTypes fractype = LM_OT_FRAC;
346 data.Insert(doAccent(yylval.i, varcode));
348 data.Insert (yylval.i, varcode); //LM_TC_VAR);
354 data.Insert(macro->getMacroPar(yylval.i-1), LM_TC_INSET);
358 case LM_TK_NEWCOMMAND:
363 // This name lives until quitting, for that reason
364 // I didn't care on deleting explicitly. Later I will.
365 char const * name = strnew(&yytext[1]);
366 // ugly trick to be removed soon (lyx3)
367 char c; yyis->get(c);
373 macro = new MathMacroTemplate(name, na);
374 flags = FLAG_BRACE|FLAG_BRACE_LAST;
376 macro->SetData(array);
381 data.Insert (yylval.i, LM_TC_SPECIAL);
387 data.Insert(doAccent(yylval.i, LM_TC_CONST));
389 data.Insert (yylval.i, LM_TC_CONST);
395 if (accent && tprev == LM_TK_ACCENT) {
396 acc_braces[acc_brace++] = brace;
399 if (flags & FLAG_BRACE_OPT) {
400 flags &= ~FLAG_BRACE_OPT;
404 if (flags & FLAG_BRACE)
405 flags &= ~FLAG_BRACE;
407 data.Insert ('{', LM_TC_TEX);
415 mathPrintError("Unmatching braces");
419 if (acc_brace && brace == acc_braces[acc_brace-1]-1) {
423 if (flags & FLAG_BRACE_FONT) {
425 yy_mtextmode = false;
426 flags &= ~FLAG_BRACE_FONT;
429 if (brace == 0 && (flags & FLAG_BRACE_LAST)) {
433 data.Insert ('}', LM_TC_TEX);
440 if (flags & FLAG_BRACK_ARG) {
441 flags &= ~FLAG_BRACK_ARG;
442 char rg = LexGetArg('[');
444 mathPrintError("Expected ']'");
448 // if (arg) strcpy(arg, yytext);
455 if (flags & FLAG_BRACK_END) {
465 MathParInset * p = new MathParInset(size, "", LM_OT_SCRIPT);
466 LyxArrayBase * ar = mathed_parse(FLAG_BRACE_OPT|FLAG_BRACE_LAST, 0);
468 // lyxerr << "UP[" << p->GetStyle() << "]" << endl;
469 data.Insert (p, LM_TC_UP);
474 MathParInset * p = new MathParInset(size, "", LM_OT_SCRIPT);
475 LyxArrayBase * ar = mathed_parse(FLAG_BRACE_OPT|FLAG_BRACE_LAST, 0);
477 data.Insert (p, LM_TC_DOWN);
484 binset->SetLimits(bool(yylval.l->id));
492 if ((flags & FLAG_END) && mt && data.getCol()<mt->GetColumns()-1) {
493 data.setNumCols(mt->GetColumns());
494 data.Insert('T', LM_TC_TAB);
496 mathPrintError("Unexpected tab");
497 // debug info. [made that conditional -JMarc]
498 if (lyxerr.debugging(Debug::MATHED))
499 lyxerr << data.getCol() << " " << mt->GetColumns() << endl;
504 if (mt && (flags & FLAG_END)) {
505 if (mt->Permit(LMPF_ALLOW_CR)) {
507 crow->setNext(new MathedRowSt(mt->GetColumns()+1)); // this leaks
508 crow = crow->getNext();
510 data.Insert('K', LM_TC_CR);
512 mathPrintError("Unexpected newline");
518 binset = new MathBigopInset(yylval.l->name, yylval.l->id);
524 if (yylval.l->id < 256) {
525 MathedTextCodes tc = MathIsBOPS(yylval.l->id) ? LM_TC_BOPS: LM_TC_SYMB;
527 data.Insert(doAccent(yylval.l->id, tc));
529 data.Insert (yylval.l->id, tc);
531 MathFuncInset * bg = new MathFuncInset(yylval.l->name);
533 data.Insert(doAccent(bg));
535 data.Insert(bg, true);
542 data.Insert(doAccent(yylval.i, LM_TC_BOP));
544 data.Insert (yylval.i, LM_TC_BOP);
550 mt->UserSetSize(yylval.l->id);
557 MathSpaceInset * sp = new MathSpaceInset(yylval.i);
564 MathDotsInset * p = new MathDotsInset(yylval.l->name, yylval.l->id);
569 fractype = LM_OT_STACKREL;
572 MathFracInset * fc = new MathFracInset(fractype);
573 LyxArrayBase * num = mathed_parse(FLAG_BRACE|FLAG_BRACE_LAST);
574 LyxArrayBase * den = mathed_parse(FLAG_BRACE|FLAG_BRACE_LAST);
575 fc->SetData(num, den);
576 data.Insert(fc, LM_TC_ACTIVE_INSET);
583 char c; yyis->get(c);
586 rt = new MathRootInset(size);
587 rt->setArgumentIdx(0);
588 rt->SetData(mathed_parse(FLAG_BRACK_END, 0, &rt));
589 rt->setArgumentIdx(1);
592 rt = new MathSqrtInset(size);
594 rt->SetData(mathed_parse(FLAG_BRACE|FLAG_BRACE_LAST, 0, &rt));
595 data.Insert(rt, LM_TC_ACTIVE_INSET);
603 if (lfd == LM_TK_SYM || lfd == LM_TK_STR || lfd == LM_TK_BOP|| lfd == LM_TK_SPECIAL)
604 lfd = (lfd == LM_TK_SYM) ? yylval.l->id: yylval.i;
605 // lyxerr << "L[" << lfd << " " << lfd << "]";
606 LyxArrayBase * a = mathed_parse(FLAG_RIGHT);
608 // lyxerr << "R[" << rgd << "]";
609 if (rgd == LM_TK_SYM || rgd == LM_TK_STR || rgd == LM_TK_BOP || rgd == LM_TK_SPECIAL)
610 rgd = (rgd == LM_TK_SYM) ? yylval.l->id: yylval.i;
611 MathDelimInset * dl = new MathDelimInset(lfd, rgd);
613 data.Insert(dl, LM_TC_ACTIVE_INSET);
614 // lyxerr << "RL[" << lfd << " " << rgd << "]";
619 if (flags & FLAG_RIGHT) {
623 mathPrintError("Unmatched right delimiter");
631 varcode = static_cast<MathedTextCodes>(yylval.l->id);
632 yy_mtextmode = bool(varcode == LM_TC_TEXTRM);
633 flags |= (FLAG_BRACE|FLAG_BRACE_FONT);
638 MathDecorationInset * sq = new MathDecorationInset(yylval.l->id,
640 sq->SetData(mathed_parse(FLAG_BRACE|FLAG_BRACE_LAST));
641 data.Insert(sq, LM_TC_ACTIVE_INSET);
645 case LM_TK_ACCENT: setAccent(yylval.l->id); break;
650 crow->setNumbered(false);
657 MathedInset * bg = new MathFuncInset(yylval.l->name);
666 data.Insert(new MathFuncInset(yylval.l->name, LM_OT_FUNCLIM));
673 MathMacroTable::mathMTable.getMacro(yylval.s);
676 data.Insert(doAccent(p), p->getTCode());
678 data.Insert(p, p->getTCode());
679 for (int i = 0; p->setArgumentIdx(i); i++)
680 p->SetData(mathed_parse(FLAG_BRACE|FLAG_BRACE_LAST));
683 MathedInset * q = new MathFuncInset(yylval.s, LM_OT_UNDEF);
685 data.Insert(doAccent(q));
694 if (mathed_env != yylval.i && yylval.i!= LM_EN_ARRAY)
695 mathPrintError("Unmatched environment");
696 // debug info [made that conditional -JMarc]
697 if (lyxerr.debugging(Debug::MATHED))
698 lyxerr << "[" << yylval.i << "]" << endl;
700 if (mt) { // && (flags & FLAG_END)) {
708 if (yylval.i == LM_EN_ARRAY) {
709 char ar[120], ar2[8];
710 ar[0] = ar2[0] = '\0';
711 char rg = LexGetArg(0);
717 int nc = parse_align(ar, ar2);
718 MathParInset * mm = new MathMatrixInset(nc, 0);
719 mm->SetAlign(ar2[0], ar);
720 data.Insert(mm, LM_TC_ACTIVE_INSET);
721 mathed_parse(FLAG_END, mm->GetData(), &mm);
723 if (yylval.i >= LM_EN_INTEXT && yylval.i<= LM_EN_EQNARRAY) {
725 mathPrintError("Misplaced environment");
729 mathPrintError("0 paragraph.");
733 mathed_env = yylval.i;
734 if (mathed_env>= LM_EN_DISPLAY) {
735 size = LM_ST_DISPLAY;
736 if (mathed_env>LM_EN_EQUATION) {
737 mt = new MathMatrixInset(3, -1);
738 mt->SetAlign(' ', "rcl");
741 // data.Insert(' ', LM_TC_TAB);
742 // data.Insert(' ', LM_TC_TAB);
746 mt->SetType(mathed_env);
747 crow = mt->getRowSt();
751 lyxerr << "MATH BEGIN[" << mathed_env << "]" << endl;
754 // lyxerr << "MATHCRO[" << yytext << "]";
756 MathMacroTable::mathMTable.getMacro(yytext);
758 data.Insert(p, p->getTCode());
759 p->setArgumentIdx(0);
760 mathed_parse(FLAG_END, p->GetData(), reinterpret_cast<MathParInset**>(&p));
761 // for (int i= 0; p->setArgumentIdx(i); i++)
762 // p->SetData(mathed_parse(FLAG_BRACE|FLAG_BRACE_LAST));
764 mathPrintError("Unrecognized environment");
772 MathMacroTable::mathMTable.getMacro(yylval.l->name);
776 data.Insert(doAccent(p));
778 data.Insert(p, static_cast<MathMacro*>(p)->getTCode());
785 char rg = LexGetArg('\0', true);
787 mathPrintError("Expected '{'");
789 lyxerr << "[" << yytext << "]" << endl;
794 // This is removed by crow's destructor. Bad design? yes, this
795 // will be changed after 0.12
796 crow->setLabel(strnew(yytext));
799 // where is this math_label free'ed?
800 // Supposedly in ~formula, another bad hack,
801 // give me some time please.
802 mathed_label = strnew(yytext);
805 lyxerr << "Label[" << mathed_label << "]" << endl;
810 mathPrintError("Unrecognized token");
812 lyxerr << "[" << t << " " << yytext << "]" << endl;
817 lyxerr << " Math Panic, expect problems!" << endl;
818 // Search for the end command.
819 do t = yylex (); while (t != LM_TK_END && t);
823 if ((flags & FLAG_BRACE_OPT)/* && t!= '^' && t!= '_'*/) {
824 flags &= ~FLAG_BRACE_OPT;
825 //data.Insert (LM_TC_CLOSE);
834 void mathed_parser_file(istream & is, int lineno)
838 if (!MathMacroTable::built)
839 MathMacroTable::mathMTable.builtinMacros();
843 int mathed_parser_lineno()