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: 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
26 #include "math_parser.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_macro.h"
35 #include "math_macrotable.h"
36 #include "math_macrotemplate.h"
37 #include "math_matrixinset.h"
38 #include "math_rootinset.h"
39 #include "math_scopeinset.h"
40 #include "math_sqrtinset.h"
41 #include "math_scriptinset.h"
42 #include "math_sqrtinset.h"
46 #include "support/lstrings.h"
54 MathScriptInset * prevScriptInset(MathArray const & array)
56 MathInset * p = array.back();
57 return (p && p->isScriptInset()) ? static_cast<MathScriptInset *>(p) : 0;
61 MathInset * lastScriptInset(MathArray & array, bool up, bool down, int limits)
63 MathScriptInset * p = prevScriptInset(array);
65 MathInset * b = array.back();
66 if (b && b->isScriptable()) {
67 p = new MathScriptInset(up, down, b->clone());
70 p = new MathScriptInset(up, down);
84 // These are lexical codes, not semantic
88 LexBOP, // Binary operators or relations
98 lexcode_enum lexcode[256];
101 const unsigned char LM_TK_OPEN = '{';
102 const unsigned char LM_TK_CLOSE = '}';
105 FLAG_BRACE = 1 << 0, // an opening brace needed
106 FLAG_BRACE_LAST = 1 << 1, // last closing brace ends the parsing process
107 FLAG_RIGHT = 1 << 2, // next right ends the parsing process
108 FLAG_END = 1 << 3, // next end ends the parsing process
109 FLAG_BRACK_END = 1 << 4, // next closing bracket ends the parsing process
110 FLAG_AMPERSAND = 1 << 5, // next & ends the parsing process
111 FLAG_NEWLINE = 1 << 6, // next \\ ends the parsing process
112 FLAG_ITEM = 1 << 7, // read a (possibly braced token)
113 FLAG_BLOCK = 1 << 8, // next block ends the parsing process
114 FLAG_LEAVE = 1 << 9, // marker for leaving the
118 struct latex_mathenv_type {
120 char const * basename;
126 latex_mathenv_type latex_mathenv[] = {
127 {"math", "math", LM_OT_SIMPLE, 0, 0},
128 {"equation*", "equation", LM_OT_EQUATION, 0, 0},
129 {"equation", "equation", LM_OT_EQUATION, 1, 0},
130 {"eqnarray*", "eqnarray", LM_OT_EQNARRAY, 0, 0},
131 {"eqnarray", "eqnarray", LM_OT_EQNARRAY, 1, 0},
132 {"align*", "align", LM_OT_ALIGN, 0, 1},
133 {"align", "align", LM_OT_ALIGN, 1, 1},
134 {"alignat*", "alignat", LM_OT_ALIGNAT, 0, 1},
135 {"alignat", "alignat", LM_OT_ALIGNAT, 1, 1},
136 {"multline*", "multline", LM_OT_MULTLINE, 0, 1},
137 {"multline", "multline", LM_OT_MULTLINE, 1, 1},
138 {"array", "array", LM_OT_MATRIX, 0, 1}
141 int const latex_mathenv_num = sizeof(latex_mathenv)/sizeof(latex_mathenv[0]);
147 for (int i = 0; i <= 255; ++i) {
149 lexcode[i] = LexOther;
151 lexcode[i] = LexSpace;
153 lexcode[i] = LexAlpha;
156 lexcode['\t'] = lexcode['\f'] = lexcode[' '] = LexSpace;
157 lexcode['\n'] = LexNewLine;
158 lexcode['%'] = LexComment;
159 lexcode['#'] = LexArgument;
160 lexcode['$'] = LexMath;
161 lexcode['+'] = lexcode['-'] = lexcode['*'] = lexcode['/']
162 = lexcode['<'] = lexcode['>'] = lexcode['='] = LexBOP;
164 lexcode['('] = lexcode[')'] = lexcode['|'] = lexcode['.'] =
165 lexcode['?'] = LexOther;
167 lexcode['\''] = lexcode['@'] = LexAlpha;
169 lexcode['['] = lexcode[']'] = lexcode['^'] = lexcode['_'] =
170 lexcode['&'] = LexSelf;
172 lexcode['{'] = LexSelf;
173 lexcode['}'] = LexSelf;
175 lexcode['\\'] = LexESC;
181 // Helper class for parsing
189 : is_(lex.getStream()), lineno_(lex.getLineNo()), putback_token_(0)
193 : is_(is), lineno_(0), putback_token_(0)
197 MathMacroTemplate * parse_macro();
199 MathMatrixInset * parse_normal();
201 void parse_into(MathArray & array, unsigned flags);
203 int lineno() const { return lineno_; }
205 void putback(int token);
211 string lexArg(unsigned char lf, bool accept_spaces = false);
213 unsigned char getuchar();
215 void error(string const & msg);
217 void parse_lines(MathGridInset * p, int col, bool numbered, bool outmost);
219 latexkeys const * read_delim();
230 latexkeys const * lval_;
246 void Parser::putback(int token)
248 putback_token_ = token;
252 unsigned char Parser::getuchar()
256 lyxerr << "The input stream is not well..." << endl;
258 return static_cast<unsigned char>(c);
262 string Parser::lexArg(unsigned char lf, bool accept_spaces)
277 unsigned char rg = 0;
278 if (lf == '{') rg = '}';
279 if (lf == '[') rg = ']';
280 if (lf == '(') rg = ')';
282 lyxerr[Debug::MATHED] << "Math parse error: unknown bracket '"
283 << lf << "'" << endl;
289 unsigned char c = getuchar();
294 if ((!isspace(c) || (c == ' ' && accept_spaces)) && depth > 0)
296 } while (depth > 0 && is_.good());
304 static bool init_done = false;
311 if (putback_token_) {
312 int token = putback_token_;
318 unsigned char c = getuchar();
320 //lyxerr << "reading byte: '" << c << "' code: " << lexcode[c] << endl;
325 if (lexcode[c] == LexNewLine) {
330 if (lexcode[c] == LexComment) {
333 } while (c != '\n' && is_.good()); // eat comments
337 if (lexcode[c] == LexOther)
340 if (lexcode[c] == LexAlpha || lexcode[c] == LexSpace)
343 if (lexcode[c] == LexBOP)
346 if (lexcode[c] == LexMath) {
351 if (lexcode[c] == LexSelf)
354 if (lexcode[c] == LexArgument) {
357 return LM_TK_ARGUMENT;
360 if (lexcode[c] == LexESC) {
362 //lyxerr << "reading second byte: '" << c
363 // << "' code: " << lexcode[c] << endl;
365 latexkeys const * l = in_word_set(s);
367 //lyxerr << "found key: " << l << endl;
368 //lyxerr << "found key name: " << l->name << endl;
369 //lyxerr << "found key token: " << l->token << endl;
374 if (lexcode[c] == LexAlpha) {
376 while (lexcode[c] == LexAlpha && is_.good()) {
380 while (lexcode[c] == LexSpace && is_.good())
382 if (lexcode[c] != LexSpace)
385 //lyxerr[Debug::MATHED] << "reading: text '" << sval_ << "'\n";
386 //lyxerr << "reading: text '" << sval_ << "'\n";
387 lval_ = in_word_set(sval_);
391 if (lval_->token == LM_TK_BEGIN || lval_->token == LM_TK_END) {
392 string name = lexArg('{');
394 while (i < latex_mathenv_num && name != latex_mathenv[i].name)
406 void Parser::error(string const & msg)
408 lyxerr << "Line ~" << lineno_ << ": Math parse error: " << msg << endl;
412 void Parser::parse_lines(MathGridInset * p, int col, bool numbered, bool outmost)
414 // save global variables
415 bool const saved_num = curr_num_;
416 string const saved_label = curr_label_;
418 for (int row = 0; true; ++row) {
419 // reset global variables
420 curr_num_ = numbered;
424 int idx = p->nargs() - p->ncols();
425 for (int i = 0; i < col - 1; ++i, ++idx)
426 parse_into(p->cell(idx), FLAG_AMPERSAND);
427 parse_into(p->cell(idx), FLAG_NEWLINE | FLAG_END);
430 MathMatrixInset * m = static_cast<MathMatrixInset *>(p);
431 m->numbered(row, curr_num_);
432 m->label(row, curr_label_);
433 if (curr_skip_.size()) {
434 m->vskip(LyXLength(curr_skip_), row);
449 // restore "global" variables
450 curr_num_ = saved_num;
451 curr_label_ = saved_label;
455 MathMacroTemplate * Parser::parse_macro()
457 if (yylex() != LM_TK_NEWCOMMAND) {
458 lyxerr << "\\newcommand expected\n";
462 string name = lexArg('{').substr(1);
463 string arg = lexArg('[');
464 int narg = arg.empty() ? 0 : atoi(arg.c_str());
465 MathMacroTemplate * p = new MathMacroTemplate(name, narg);
466 parse_into(p->cell(0), FLAG_BRACE | FLAG_BRACE_LAST);
471 MathMatrixInset * Parser::parse_normal()
473 MathMatrixInset * p = 0;
480 lyxerr[Debug::MATHED]
481 << "reading math environment " << i << " "
482 << latex_mathenv[i].name << "\n";
484 MathInsetTypes typ = latex_mathenv[i].typ;
485 p = new MathMatrixInset(typ);
490 curr_num_ = latex_mathenv[i].numbered;
492 parse_into(p->cell(0), 0);
493 p->numbered(0, curr_num_);
494 p->label(0, curr_label_);
498 case LM_OT_EQUATION: {
499 curr_num_ = latex_mathenv[i].numbered;
501 parse_into(p->cell(0), FLAG_END);
502 p->numbered(0, curr_num_);
503 p->label(0, curr_label_);
507 case LM_OT_EQNARRAY: {
508 parse_lines(p, 3, latex_mathenv[i].numbered, true);
513 p->halign(lexArg('{'));
514 parse_lines(p, 2, latex_mathenv[i].numbered, true);
518 case LM_OT_ALIGNAT: {
519 p->halign(lexArg('{'));
520 parse_lines(p, 2, latex_mathenv[i].numbered, true);
525 lyxerr[Debug::MATHED]
526 << "1: unknown math environment: " << typ << "\n";
533 lyxerr[Debug::MATHED]
534 << "2 unknown math environment: " << t << "\n";
541 latexkeys const * Parser::read_delim()
544 //lyxerr << "found symbol: " << ld << "\n";
545 latexkeys const * l = in_word_set(".");
552 //lyxerr << "found key 1: '" << l << "'\n";
553 //lyxerr << "found key 1: '" << l->name << "'\n";
561 //lyxerr << "found key 2: '" << l->name << "'\n";
568 //lyxerr << "found key 2: '" << l->name << "'\n";
575 void Parser::parse_into(MathArray & array, unsigned flags)
577 MathTextCodes yyvarcode = LM_TC_VAR;
582 while (int t = yylex()) {
584 //lyxerr << "t: " << t << " flags: " << flags << " i: " << ival_
585 // << " '" << sval_ << "'\n";
586 //array.dump(lyxerr);
589 if (flags & FLAG_ITEM) {
591 if (t == LM_TK_OPEN) {
592 // skip the brace and collect everything to the next matching
594 flags |= FLAG_BRACE_LAST;
597 // handle only this single token, leave the loop if done
602 if (flags & FLAG_BRACE) {
603 if (t != LM_TK_OPEN) {
604 error("Expected {. Maybe you forgot to enclose an argument in {}");
608 flags &= ~FLAG_BRACE;
613 if (flags & FLAG_BLOCK) {
614 if (t == LM_TK_CLOSE || t == '&' || t == LM_TK_NEWLINE || t == LM_TK_END){
628 if (!isspace(ival_) || yyvarcode == LM_TC_TEXTRM)
629 array.push_back(new MathCharInset(ival_, yyvarcode));
632 case LM_TK_ARGUMENT: {
633 MathMacroArgument * p = new MathMacroArgument(ival_);
634 //p->code(yyvarcode);
640 array.push_back(new MathCharInset(ival_, LM_TC_SPECIAL));
644 array.push_back(new MathCharInset(ival_, LM_TC_CONST));
648 //lyxerr << " creating ScopeInset\n";
649 array.push_back(new MathScopeInset);
650 parse_into(array.back()->cell(0), FLAG_BRACE_LAST);
654 if (flags & FLAG_BRACE_LAST)
659 array.push_back(new MathCharInset('[', LM_TC_CONST));
663 if (flags & FLAG_BRACK_END)
666 array.push_back(new MathCharInset(']', LM_TC_CONST));
671 lastScriptInset(array, true, false, limits)->cell(0), FLAG_ITEM);
676 lastScriptInset(array, false, true, limits)->cell(1), FLAG_ITEM);
681 //lyxerr << "setting limit to " << limits << "\n";
685 if (flags & FLAG_AMPERSAND) {
686 flags &= ~FLAG_AMPERSAND;
689 lyxerr[Debug::MATHED]
690 << "found tab unexpectedly, array: '" << array << "'\n";
695 curr_skip_ = lexArg('[');
696 if (flags & FLAG_NEWLINE) {
697 flags &= ~FLAG_NEWLINE;
700 lyxerr[Debug::MATHED]
701 << "found newline unexpectedly, array: '" << array << "'\n";
709 array.push_back(new MathCharInset(ival_, LM_TC_BOP));
714 unsigned char c = getuchar();
716 array.push_back(new MathRootInset);
717 parse_into(array.back()->cell(0), FLAG_BRACK_END);
718 parse_into(array.back()->cell(1), FLAG_ITEM);
721 array.push_back(new MathSqrtInset);
722 parse_into(array.back()->cell(0), FLAG_ITEM);
729 latexkeys const * l = read_delim();
731 parse_into(ar, FLAG_RIGHT);
732 latexkeys const * r = read_delim();
733 MathDelimInset * dl = new MathDelimInset(l, r);
740 if (flags & FLAG_RIGHT)
742 error("Unmatched right delimiter");
748 MathTextCodes t = static_cast<MathTextCodes>(lval_->id);
750 parse_into(ar, FLAG_ITEM);
751 for (MathArray::iterator it = ar.begin(); it != ar.end(); ++it)
752 (*it)->handleFont(t);
758 yyvarcode = static_cast<MathTextCodes>(lval_->id);
763 lyxerr[Debug::MATHED] << "LM_TK_STY not implemented\n";
764 //MathArray tmp = array;
765 //MathSizeInset * p = new MathSizeInset(MathStyles(lval_->id));
766 //array.push_back(p);
767 //parse_into(p->cell(0), FLAG_BRACE_FONT);
776 if (MathMacroTable::hasTemplate(sval_)) {
777 MathMacro * m = MathMacroTable::cloneTemplate(sval_);
778 for (int i = 0; i < m->nargs(); ++i)
779 parse_into(m->cell(i), FLAG_ITEM);
781 m->metrics(LM_ST_TEXT);
783 array.push_back(new MathFuncInset(sval_));
789 MathInsetTypes typ = latex_mathenv[i].typ;
791 if (typ == LM_OT_MATRIX) {
792 string const valign = lexArg('[') + 'c';
793 string const halign = lexArg('{');
794 //lyxerr << "valign: '" << valign << "'\n";
795 //lyxerr << "halign: '" << halign << "'\n";
796 MathArrayInset * m = new MathArrayInset(halign.size(), 1);
797 m->valign(valign[0]);
800 parse_lines(m, halign.size(), latex_mathenv[i].numbered, false);
802 //lyxerr << "read matrix " << *m << "\n";
805 lyxerr[Debug::MATHED] << "unknow math inset " << typ << "\n";
810 curr_label_ = lexArg('{', true);
817 MathInset * p = createMathInset(lval_);
818 p->cell(0).swap(array);
820 parse_into(p->cell(1), FLAG_BLOCK);
826 MathInset * p = createMathInset(lval_);
828 for (int i = 0; i < p->nargs(); ++i)
829 parse_into(p->cell(i), FLAG_ITEM);
832 error("Unrecognized token");
833 //lyxerr[Debug::MATHED] << "[" << t << " " << sval_ << "]\n";
834 lyxerr << "[" << t << " " << sval_ << "]\n";
837 } // end of big switch
839 if (flags & FLAG_LEAVE) {
840 flags &= ~FLAG_LEAVE;
846 lyxerr << " Math Panic, expect problems!\n";
847 // Search for the end command.
851 } while (is_.good() && t != LM_TK_END && t);
856 void parse_end(LyXLex & lex, int lineno)
858 // Update line number
859 lex.setLineNo(lineno);
861 // reading of end_inset
864 if (lex.getString() == "\\end_inset")
866 //lyxerr[Debug::MATHED] << "InsetFormula::Read: Garbage before \\end_inset,"
867 lyxerr << "InsetFormula::Read: Garbage before \\end_inset,"
868 " or missing \\end_inset!\n";
872 } // anonymous namespace
876 MathArray mathed_parse_cell(string const & str)
878 istringstream is(str.c_str());
881 parser.parse_into(ar, 0);
887 MathMacroTemplate * mathed_parse_macro(string const & str)
889 istringstream is(str.c_str());
891 return parser.parse_macro();
894 MathMacroTemplate * mathed_parse_macro(istream & is)
897 return parser.parse_macro();
900 MathMacroTemplate * mathed_parse_macro(LyXLex & lex)
903 MathMacroTemplate * p = parser.parse_macro();
904 parse_end(lex, parser.lineno());
910 MathMatrixInset * mathed_parse_normal(string const & str)
912 istringstream is(str.c_str());
914 return parser.parse_normal();
917 MathMatrixInset * mathed_parse_normal(istream & is)
920 return parser.parse_normal();
923 MathMatrixInset * mathed_parse_normal(LyXLex & lex)
926 MathMatrixInset * p = parser.parse_normal();
927 parse_end(lex, parser.lineno());