1 /** The .tex to .lyx converter
2 \author André Pönitz (2003)
19 #include "texparser.h"
30 using std::istringstream;
32 using std::ostringstream;
40 char const OPEN = '<';
41 char const CLOSE = '>';
42 char const TAB = '\001';
43 char const LINE = '\002';
45 const char * known_languages[] = { "austrian", "babel", "bahasa", "basque",
46 "breton", "british", "bulgarian", "catalan", "croatian", "czech",
47 "danish", "dutch", "english", "esperanto", "estonian", "finnish",
48 "francais", "frenchb", "galician", "germanb", "greek", "hebcal", "hebfont",
49 "hebrew", "hebrew_newcode", "hebrew_oldcode", "hebrew_p", "hyphen",
50 "icelandic", "irish", "italian", "latin", "lgrcmr", "lgrcmro", "lgrcmss",
51 "lgrcmtt", "lgrenc", "lgrlcmss", "lgrlcmtt", "lheclas", "lhecmr",
52 "lhecmss", "lhecmtt", "lhecrml", "lheenc", "lhefr", "lheredis", "lheshold",
53 "lheshscr", "lheshstk", "lsorbian", "magyar", "naustrian", "ngermanb",
54 "ngerman", "norsk", "polish", "portuges", "rlbabel", "romanian",
55 "russianb", "samin", "scottish", "serbian", "slovak", "slovene", "spanish",
56 "swedish", "turkish", "ukraineb", "usorbian", "welsh", 0};
58 const char * known_fontsizes[] = { "10pt", "11pt", "12pt", 0 };
61 const char * known_math_envs[] = {"equation", "eqnarray", "eqnarray*",
62 "align", "align*", 0};
66 ostringstream h_preamble;
67 string h_textclass = "article";
68 string h_options = "";
69 string h_language = "english";
70 string h_inputencoding = "latin1";
71 string h_fontscheme = "default";
72 string h_graphics = "default";
73 string h_paperfontsize = "default";
74 string h_spacing = "single";
75 string h_papersize = "default";
76 string h_paperpackage = "default";
77 string h_use_geometry = "0";
78 string h_use_amsmath = "0";
79 string h_use_natbib = "0";
80 string h_use_numerical_citations = "0";
81 string h_paperorientation = "portrait";
82 string h_secnumdepth = "3";
83 string h_tocdepth = "3";
84 string h_paragraph_separation = "indent";
85 string h_defskip = "medskip";
86 string h_quotes_language = "english";
87 string h_quotes_times = "1";
88 string h_papercolumns = "1";
89 string h_papersides = "1";
90 string h_paperpagestyle = "default";
91 string h_tracking_changes = "0";
93 // indicates whether we are in the preamble
94 bool in_preamble = true;
96 // current stack of nested environments
97 stack<string> active_environments;
103 s[0] = toupper(s[0]);
108 string const trim(string const & a, char const * p = " ")
112 if (a.empty() || !*p)
115 string::size_type r = a.find_last_not_of(p);
116 string::size_type l = a.find_first_not_of(p);
118 // Is this the minimal test? (lgb)
119 if (r == string::npos && l == string::npos)
122 return a.substr(l, r - l + 1);
126 void split(string const & s, vector<string> & result, char delim)
130 while (getline(is, t, delim))
135 string join(vector<string> const & input, char delim)
138 for (size_t i = 0; i != input.size(); ++i) {
147 void handle_opt(vector<string> & opts, char const ** what, string & target)
152 for ( ; *what; ++what) {
153 vector<string>::iterator it = find(opts.begin(), opts.end(), *what);
154 if (it != opts.end()) {
155 //cerr << "### found option '" << *what << "'\n";
164 bool is_math_env(string const & name)
166 for (char const ** what = known_math_envs; *what; ++what)
173 bool is_heading(string const & name)
179 name == "paragraph" ||
182 name == "subsection" ||
183 name == "subsubsection";
187 bool is_latex_command(string const & name)
194 name == "printindex";
198 void begin_inset(ostream & os, string const & name)
200 os << "\n\\begin_inset " << name;
204 void end_inset(ostream & os)
206 os << "\n\\end_inset\n";
212 return active_environments.empty() ? string() : active_environments.top();
216 void handle_ert(ostream & os, string const & s)
218 begin_inset(os, "ERT");
219 os << "\nstatus Collapsed\n\n\\layout Standard\n\n";
220 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
222 os << "\n\\backslash\n";
230 void handle_par(ostream & os)
232 if (active_environments.empty())
235 string s = curr_env();
236 if (s == "document" || s == "table") {
237 os << "Standard\n\n";
240 if (s == "lyxcode") {
241 os << "LyX-Code\n\n";
244 os << cap(s) << "\n\n";
248 void handle_package(string const & name, string const & options)
250 if (name == "a4wide") {
251 h_papersize = "a4paper";
252 h_paperpackage = "widemarginsa4";
253 } else if (name == "ae")
255 else if (name == "aecompl")
257 else if (name == "amsmath")
259 else if (name == "amssymb")
261 else if (name == "babel")
263 else if (name == "fontenc")
265 else if (name == "inputenc")
266 h_inputencoding = options;
267 else if (name == "makeidx")
269 else if (name == "verbatim")
273 h_preamble << "\\usepackage[" << options << "]{" << name << "}\n";
275 h_preamble << "\\usepackage{" << name << "}\n";
280 void handle_table(Parser &, ostream &)
282 // \begin{table} has been read
287 string wrap(string const & cmd, string const & str)
289 return OPEN + cmd + ' ' + str + CLOSE;
293 vector<string> extract_col_align(string const & s)
296 for (size_t i = 0; i < s.size(); ++i) {
299 res.push_back("center");
302 res.push_back("left");
305 res.push_back("right");
308 res.push_back("right");
316 void end_preamble(ostream & os)
319 os << "# tex2lyx 0.0.2 created this file\n"
320 << "\\lyxformat 222\n"
321 << "\\textclass " << h_textclass << "\n"
322 << "\\begin_preamble\n" << h_preamble.str() << "\n\\end_preamble\n"
323 << "\\options " << h_options << "\n"
324 << "\\language " << h_language << "\n"
325 << "\\inputencoding " << h_inputencoding << "\n"
326 << "\\fontscheme " << h_fontscheme << "\n"
327 << "\\graphics " << h_graphics << "\n"
328 << "\\paperfontsize " << h_paperfontsize << "\n"
329 << "\\spacing " << h_spacing << "\n"
330 << "\\papersize " << h_papersize << "\n"
331 << "\\paperpackage " << h_paperpackage << "\n"
332 << "\\use_geometry " << h_use_geometry << "\n"
333 << "\\use_amsmath " << h_use_amsmath << "\n"
334 << "\\use_natbib " << h_use_natbib << "\n"
335 << "\\use_numerical_citations " << h_use_numerical_citations << "\n"
336 << "\\paperorientation " << h_paperorientation << "\n"
337 << "\\secnumdepth " << h_secnumdepth << "\n"
338 << "\\tocdepth " << h_tocdepth << "\n"
339 << "\\paragraph_separation " << h_paragraph_separation << "\n"
340 << "\\defskip " << h_defskip << "\n"
341 << "\\quotes_language " << h_quotes_language << "\n"
342 << "\\quotes_times " << h_quotes_times << "\n"
343 << "\\papercolumns " << h_papercolumns << "\n"
344 << "\\papersides " << h_papersides << "\n"
345 << "\\paperpagestyle " << h_paperpagestyle << "\n"
346 << "\\tracking_changes " << h_tracking_changes << "\n";
350 void parse(Parser & p, ostream & os, unsigned flags, mode_type mode)
353 Token const & t = p.getToken();
356 cerr << "t: " << t << " flags: " << flags << "\n";
360 if (flags & FLAG_ITEM) {
361 if (t.cat() == catSpace)
365 if (t.cat() == catBegin) {
366 // skip the brace and collect everything to the next matching
368 flags |= FLAG_BRACE_LAST;
372 // handle only this single token, leave the loop if done
377 if (flags & FLAG_BRACED) {
378 if (t.cat() == catSpace)
381 if (t.cat() != catBegin) {
382 p.error("opening brace expected");
386 // skip the brace and collect everything to the next matching
388 flags = FLAG_BRACE_LAST;
392 if (flags & FLAG_OPTION) {
393 if (t.cat() == catOther && t.character() == '[') {
394 parse(p, os, FLAG_BRACK_LAST, mode);
396 // no option found, put back token and we are done
405 if (t.cat() == catMath) {
406 if (mode == TEXT_MODE || mode == MATHTEXT_MODE) {
407 // we are inside some text mode thingy, so opening new math is allowed
408 if (mode == TEXT_MODE)
409 begin_inset(os, "Formula ");
410 Token const & n = p.getToken();
411 if (n.cat() == catMath) {
412 // TeX's $$...$$ syntax for displayed math
414 parse(p, os, FLAG_SIMPLE, MATH_MODE);
416 p.getToken(); // skip the second '$' token
418 // simple $...$ stuff
421 parse(p, os, FLAG_SIMPLE, MATH_MODE);
424 if (mode == TEXT_MODE)
428 else if (flags & FLAG_SIMPLE) {
429 // this is the end of the formula
434 cerr << "mode: " << mode << endl;
435 p.error("something strange in the parser\n");
440 else if (t.cat() == catLetter)
443 else if (t.cat() == catSpace)
446 else if (t.cat() == catNewline)
449 else if (t.cat() == catSuper)
452 else if (t.cat() == catSub)
455 else if (t.cat() == catParameter) {
456 Token const & n = p.getToken();
457 os << wrap("macroarg", string(1, n.character()));
460 else if (t.cat() == catActive) {
461 if (t.character() == '~')
462 os << (curr_env() == "lyxcode" ? ' ' : '~');
467 else if (t.cat() == catBegin) {
468 if (mode == MATH_MODE)
474 else if (t.cat() == catEnd) {
475 if (flags & FLAG_BRACE_LAST)
477 if (mode == MATH_MODE)
483 else if (t.cat() == catAlign) {
484 if (mode == MATH_MODE)
490 else if (t.cs() == "tabularnewline") {
491 if (mode == MATH_MODE)
497 else if (t.character() == ']' && (flags & FLAG_BRACK_LAST)) {
498 //cerr << "finished reading option\n";
502 else if (t.cat() == catOther)
503 os << string(1, t.character());
505 else if (t.cat() == catComment) {
508 Token const & t = p.getToken();
509 if (t.cat() == catNewline)
513 //os << wrap("comment", s);
521 else if (t.cs() == "lyxlock")
524 else if (t.cs() == "newcommand" || t.cs() == "providecommand") {
525 string const name = p.verbatimItem();
526 string const opts = p.getArg('[', ']');
527 string const body = p.verbatimItem();
528 // only non-lyxspecific stuff
529 if (name != "\\noun " && name != "\\tabularnewline ") {
530 ostream & out = in_preamble ? h_preamble : os;
532 begin_inset(os, "FormulaMacro\n");
533 out << "\\" << t.cs() << "{" << name << "}";
535 out << "[" << opts << "]";
536 out << "{" << body << "}";
542 else if (t.cs() == "(") {
543 begin_inset(os, "Formula");
545 parse(p, os, FLAG_SIMPLE2, MATH_MODE);
550 else if (t.cs() == "[") {
551 begin_inset(os, "Formula");
553 parse(p, os, FLAG_EQUATION, MATH_MODE);
558 else if (t.cs() == "protect")
559 // ignore \\protect, will hopefully be re-added during output
562 else if (t.cs() == "begin") {
563 string const name = p.getArg('{', '}');
564 active_environments.push(name);
565 if (name == "document") {
567 parse(p, os, FLAG_END, mode);
568 } else if (name == "abstract") {
570 parse(p, os, FLAG_END, mode);
571 } else if (is_math_env(name)) {
572 begin_inset(os, "Formula ");
573 os << "\\begin{" << name << "}";
574 parse(p, os, FLAG_END, MATH_MODE);
575 os << "\\end{" << name << "}";
577 } else if (name == "tabular") {
578 begin_inset(os, "Tabular \n");
579 string colopts = p.verbatimItem();
580 vector<string> colalign = extract_col_align(colopts);
582 parse(p, ss, FLAG_END, mode);
583 vector<string> lines;
584 split(ss.str(), lines, LINE);
585 const size_t cols = colalign.size();
586 const size_t rows = lines.size();
587 os << "<lyxtabular version=\"3\" rows=\"" << rows
588 << "\" columns=\"" << cols << "\">\n"
590 for (size_t c = 0; c < cols; ++c)
591 os << "<column alignment=\"" << colalign[c] << "\""
592 << " valignment=\"top\""
595 for (size_t r = 0; r < rows; ++r) {
596 vector<string> cells;
597 split(lines[r], cells, TAB);
598 while (cells.size() < cols)
599 cells.push_back(string());
600 //os << "<row bottomline=\"true\">\n";
602 for (size_t c = 0; c < cols; ++c) {
603 os << "<cell alignment=\"center\""
604 << " valignment=\"top\""
605 << " topline=\"true\""
606 << " leftline=\"true\""
607 << " usebox=\"none\""
609 begin_inset(os, "Text");
610 os << "\n\n\\layout Standard\n\n";
617 os << "</lyxtabular>\n";
619 } else if (name == "table") {
620 begin_inset(os, "Float table\n");
622 << "collapsed false\n"
624 << "\\layout Standard\n";
625 parse(p, os, FLAG_END, mode);
627 } else if (name == "thebibliography") {
628 p.verbatimItem(); // swallow next arg
629 parse(p, os, FLAG_END, mode);
630 os << "\n\\layout Standard\n\n";
631 } else if (mode == MATH_MODE) {
632 os << "\\begin{" << name << "}";
633 parse(p, os, FLAG_END, mode);
634 os << "\\end{" << name << "}";
636 parse(p, os, FLAG_END, mode);
640 else if (t.cs() == "end") {
641 if (flags & FLAG_END) {
642 // eat environment name
643 string const name = p.getArg('{', '}');
644 if (name != curr_env())
645 p.error("\\end{" + name + "} does not match \\begin{"
647 active_environments.pop();
650 p.error("found 'end' unexpectedly");
653 else if (t.cs() == "item")
656 else if (t.cs() == ")") {
657 if (flags & FLAG_SIMPLE2)
659 p.error("found '\\)' unexpectedly");
662 else if (t.cs() == "]") {
663 if (flags & FLAG_EQUATION)
665 p.error("found '\\]' unexpectedly");
668 else if (t.cs() == "documentclass") {
670 split(p.getArg('[', ']'), opts, ',');
671 handle_opt(opts, known_languages, h_language);
672 handle_opt(opts, known_fontsizes, h_paperfontsize);
673 h_quotes_language = h_language;
674 h_options = join(opts, ',');
675 h_textclass = p.getArg('{', '}');
678 else if (t.cs() == "usepackage") {
679 string const options = p.getArg('[', ']');
680 string const name = p.getArg('{', '}');
681 if (options.empty() && name.find(',')) {
682 vector<string> vecnames;
683 split(name, vecnames, ',');
684 vector<string>::const_iterator it = vecnames.begin();
685 vector<string>::const_iterator end = vecnames.end();
686 for (; it != end; ++it)
687 handle_package(trim(*it), string());
689 handle_package(name, options);
693 else if (t.cs() == "newenvironment") {
694 string const name = p.getArg('{', '}');
696 string const begin = p.verbatimItem();
698 string const end = p.verbatimItem();
700 if (name != "lyxcode")
701 os << wrap("newenvironment", begin + end);
704 else if (t.cs() == "def") {
705 string name = p.getToken().cs();
706 while (p.nextToken().cat() != catBegin)
707 name += p.getToken().asString();
708 handle_ert(os, "\\def\\" + name + '{' + p.verbatimItem() + '}');
711 else if (t.cs() == "setcounter") {
712 string const name = p.getArg('{', '}');
713 string const content = p.getArg('{', '}');
714 if (name == "secnumdepth")
715 h_secnumdepth = content;
716 else if (name == "tocdepth")
717 h_tocdepth = content;
719 h_preamble << "\\setcounter{" << name << "}{" << content << "}\n";
722 else if (t.cs() == "setlength") {
723 string const name = p.getToken().cs();
724 string const content = p.getArg('{', '}');
725 if (name == "parskip")
726 h_paragraph_separation = "skip";
727 else if (name == "parindent")
728 h_paragraph_separation = "skip";
730 h_preamble << "\\setlength{" << name << "}{" << content << "}\n";
733 else if (t.cs() == "par")
736 else if (is_heading(t.cs())) {
737 string name = t.cs();
738 if (p.nextToken().asInput() == "*") {
742 os << "\\layout " << cap(name) << "\n\n";
743 parse(p, os, FLAG_ITEM, mode);
746 else if (t.cs() == "makeindex" || t.cs() == "maketitle")
749 else if (t.cs() == "tableofcontents")
750 p.verbatimItem(); // swallow this
752 else if (t.cs() == "textrm") {
753 os << '\\' << t.cs() << '{';
754 parse(p, os, FLAG_ITEM, MATHTEXT_MODE);
758 else if ((t.cs() == "emph" || t.cs() == "noun") && mode == TEXT_MODE) {
759 os << "\n\\" << t.cs() << " on\n";
760 parse(p, os, FLAG_ITEM, mode);
761 os << "\n\\" << t.cs() << " default\n";
764 else if (is_latex_command(t.cs()) && mode == TEXT_MODE) {
765 begin_inset(os, "LatexCommand ");
766 os << '\\' << t.cs() << '{';
767 parse(p, os, FLAG_ITEM, TEXT_MODE);
772 else if (t.cs() == "bibitem") {
773 os << "\n\\layout Bibliography\n\\bibitem ";
774 string opt = p.getArg('[',']');
776 os << '[' << opt << ']';
777 os << '{' << p.getArg('{','}') << '}' << "\n\n";
780 else if (t.cs() == "textasciitilde")
783 else if (t.cs() == "_" && mode == TEXT_MODE)
786 else if (t.cs() == "&" && mode == TEXT_MODE)
789 else if (t.cs() == "pagestyle" && in_preamble)
790 h_paperpagestyle == p.getArg('{','}');
793 if (mode == MATH_MODE)
795 else if (in_preamble)
796 h_preamble << t.asInput();
798 // heuristic: read up to next non-nested space
800 string s = t.asInput();
801 string z = p.verbatimItem();
802 while (p.good() && z != " " && z.size()) {
803 //cerr << "read: " << z << endl;
805 z = p.verbatimItem();
807 cerr << "found ERT: " << s << endl;
808 handle_ert(os, s + ' ');
810 handle_ert(os, t.asInput() + ' ');
814 if (flags & FLAG_LEAVE) {
815 flags &= ~FLAG_LEAVE;
823 } // anonymous namespace
826 int main(int argc, char * argv[])
829 cerr << "Usage: " << argv[0] << " <infile.tex>" << endl;
833 ifstream is(argv[1]);
835 parse(p, cout, 0, TEXT_MODE);
836 cout << "\n\\the_end";