1 /** The .tex to .lyx converter
2 \author André Pönitz (2003)
18 #include "texparser.h"
29 using std::istringstream;
31 using std::ostringstream;
39 char const OPEN = '<';
40 char const CLOSE = '>';
41 char const TAB = '\001';
42 char const LINE = '\002';
44 const char * known_languages[] = { "austrian", "babel", "bahasa", "basque",
45 "breton", "british", "bulgarian", "catalan", "croatian", "czech",
46 "danish", "dutch", "english", "esperanto", "estonian", "finnish",
47 "francais", "frenchb", "galician", "germanb", "greek", "hebcal", "hebfont",
48 "hebrew", "hebrew_newcode", "hebrew_oldcode", "hebrew_p", "hyphen",
49 "icelandic", "irish", "italian", "latin", "lgrcmr", "lgrcmro", "lgrcmss",
50 "lgrcmtt", "lgrenc", "lgrlcmss", "lgrlcmtt", "lheclas", "lhecmr",
51 "lhecmss", "lhecmtt", "lhecrml", "lheenc", "lhefr", "lheredis", "lheshold",
52 "lheshscr", "lheshstk", "lsorbian", "magyar", "naustrian", "ngermanb",
53 "ngerman", "norsk", "polish", "portuges", "rlbabel", "romanian",
54 "russianb", "samin", "scottish", "serbian", "slovak", "slovene", "spanish",
55 "swedish", "turkish", "ukraineb", "usorbian", "welsh", 0};
57 const char * known_fontsizes[] = { "10pt", "11pt", "12pt", 0 };
60 const char * known_math_envs[] = {"equation", "eqnarray", "eqnarray*",
61 "align", "align*", 0};
65 ostringstream h_preamble;
66 string h_textclass = "FIXME";
67 string h_options = "FIXME";
68 string h_language = "FIXME";
69 string h_inputencoding = "FIXME";
70 string h_fontscheme = "FIXME";
71 string h_graphics = "default";
72 string h_paperfontsize = "FIXME";
73 string h_spacing = "single";
74 string h_papersize = "FIXME";
75 string h_paperpackage = "FIXME";
76 string h_use_geometry = "0";
77 string h_use_amsmath = "0";
78 string h_use_natbib = "0";
79 string h_use_numerical_citations = "0";
80 string h_paperorientation = "portrait";
81 string h_secnumdepth = "3";
82 string h_tocdepth = "3";
83 string h_paragraph_separation = "indent";
84 string h_defskip = "medskip";
85 string h_quotes_language = "FIXME";
86 string h_quotes_times = "1";
87 string h_papercolumns = "1";
88 string h_papersides = "1";
89 string h_paperpagestyle = "default";
90 string h_tracking_changes = "0";
92 // indicates whether we are in the preamble
93 bool in_preamble = true;
95 // current stack of nested environments
96 stack<string> active_environments;
102 s[0] = toupper(s[0]);
107 string const trim(string const & a, char const * p = " ")
111 if (a.empty() || !*p)
114 string::size_type r = a.find_last_not_of(p);
115 string::size_type l = a.find_first_not_of(p);
117 // Is this the minimal test? (lgb)
118 if (r == string::npos && l == string::npos)
121 return a.substr(l, r - l + 1);
125 void split(string const & s, vector<string> & result, char delim)
129 while (getline(is, t, delim))
134 string join(vector<string> const & input, char delim)
137 for (size_t i = 0; i != input.size(); ++i) {
146 void handle_opt(vector<string> & opts, char const ** what, string & target)
151 for ( ; *what; ++what) {
152 vector<string>::iterator it = find(opts.begin(), opts.end(), *what);
153 if (it != opts.end()) {
154 //cerr << "### found option '" << *what << "'\n";
163 bool is_math_env(string const & name)
165 for (char const ** what = known_math_envs; *what; ++what)
172 bool is_heading(string const & name)
178 name == "paragraph" ||
180 name == "chapter*" ||
182 name == "section*" ||
183 name == "subsection" ||
184 name == "subsection*" ||
185 name == "subsubsection" ||
186 name == "subsubsection*";
190 bool is_latex_command(string const & name)
197 name == "printindex";
201 void begin_inset(ostream & os, string const & name)
203 os << "\n\\begin_inset " << name;
207 void end_inset(ostream & os)
209 os << "\n\\end_inset\n";
215 return active_environments.empty() ? string() : active_environments.top();
219 void handle_ert(ostream & os, string const & s)
221 begin_inset(os, "ERT");
222 os << "\nstatus Collapsed\n\n\\layout Standard\n\n";
223 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
225 os << "\n\\backslash\n";
233 void handle_par(ostream & os)
235 if (active_environments.empty())
238 string s = curr_env();
239 if (s == "document" || s == "table") {
240 os << "Standard\n\n";
243 if (s == "lyxcode") {
244 os << "LyX-Code\n\n";
247 os << cap(s) << "\n\n";
251 void handle_package(string const & name, string const & options)
253 if (name == "a4wide") {
254 h_papersize = "a4paper";
255 h_paperpackage = "widemarginsa4";
256 } else if (name == "ae")
258 else if (name == "aecompl")
260 else if (name == "amsmath")
262 else if (name == "amssymb")
264 else if (name == "babel")
266 else if (name == "fontenc")
268 else if (name == "inputenc")
269 h_inputencoding = options;
270 else if (name == "makeidx")
272 else if (name == "verbatim")
276 h_preamble << "\\usepackage[" << options << "]{" << name << "}\n";
278 h_preamble << "\\usepackage{" << name << "}\n";
283 void handle_table(Parser &, ostream &)
285 // \begin{table} has been read
290 string wrap(string const & cmd, string const & str)
292 return OPEN + cmd + ' ' + str + CLOSE;
296 vector<string> extract_col_align(string const & s)
299 for (size_t i = 0; i < s.size(); ++i) {
302 res.push_back("center");
305 res.push_back("left");
308 res.push_back("right");
311 res.push_back("right");
319 void end_preamble(ostream & os)
322 os << "# tex2lyx 0.0.2 created this file\n"
323 << "\\lyxformat 222\n"
324 << "\\textclass " << h_textclass << "\n"
325 << "\\begin_preamble\n" << h_preamble.str() << "\n\\end_preamble\n"
326 << "\\options " << h_options << "\n"
327 << "\\language " << h_language << "\n"
328 << "\\inputencoding " << h_inputencoding << "\n"
329 << "\\fontscheme " << h_fontscheme << "\n"
330 << "\\graphics " << h_graphics << "\n"
331 << "\\paperfontsize " << h_paperfontsize << "\n"
332 << "\\spacing " << h_spacing << "\n"
333 << "\\papersize " << h_papersize << "\n"
334 << "\\paperpackage " << h_paperpackage << "\n"
335 << "\\use_geometry " << h_use_geometry << "\n"
336 << "\\use_amsmath " << h_use_amsmath << "\n"
337 << "\\use_natbib " << h_use_natbib << "\n"
338 << "\\use_numerical_citations " << h_use_numerical_citations << "\n"
339 << "\\paperorientation " << h_paperorientation << "\n"
340 << "\\secnumdepth " << h_secnumdepth << "\n"
341 << "\\tocdepth " << h_tocdepth << "\n"
342 << "\\paragraph_separation " << h_paragraph_separation << "\n"
343 << "\\defskip " << h_defskip << "\n"
344 << "\\quotes_language " << h_quotes_language << "\n"
345 << "\\quotes_times " << h_quotes_times << "\n"
346 << "\\papercolumns " << h_papercolumns << "\n"
347 << "\\papersides " << h_papersides << "\n"
348 << "\\paperpagestyle " << h_paperpagestyle << "\n"
349 << "\\tracking_changes " << h_tracking_changes << "\n";
353 void parse(Parser & p, ostream & os, unsigned flags, mode_type mode)
356 Token const & t = p.getToken();
359 cerr << "t: " << t << " flags: " << flags << "\n";
363 if (flags & FLAG_ITEM) {
364 if (t.cat() == catSpace)
368 if (t.cat() == catBegin) {
369 // skip the brace and collect everything to the next matching
371 flags |= FLAG_BRACE_LAST;
375 // handle only this single token, leave the loop if done
380 if (flags & FLAG_BRACED) {
381 if (t.cat() == catSpace)
384 if (t.cat() != catBegin) {
385 p.error("opening brace expected");
389 // skip the brace and collect everything to the next matching
391 flags = FLAG_BRACE_LAST;
395 if (flags & FLAG_OPTION) {
396 if (t.cat() == catOther && t.character() == '[') {
397 parse(p, os, FLAG_BRACK_LAST, mode);
399 // no option found, put back token and we are done
408 if (t.cat() == catMath) {
409 if (mode == TEXT_MODE || mode == MATHTEXT_MODE) {
410 // we are inside some text mode thingy, so opening new math is allowed
411 if (mode == TEXT_MODE)
412 begin_inset(os, "Formula ");
413 Token const & n = p.getToken();
414 if (n.cat() == catMath) {
415 // TeX's $$...$$ syntax for displayed math
417 parse(p, os, FLAG_SIMPLE, MATH_MODE);
419 p.getToken(); // skip the second '$' token
421 // simple $...$ stuff
424 parse(p, os, FLAG_SIMPLE, MATH_MODE);
427 if (mode == TEXT_MODE)
431 else if (flags & FLAG_SIMPLE) {
432 // this is the end of the formula
437 cerr << "mode: " << mode << endl;
438 p.error("something strange in the parser\n");
443 else if (t.cat() == catLetter)
446 else if (t.cat() == catSpace)
449 else if (t.cat() == catNewline)
452 else if (t.cat() == catSuper)
455 else if (t.cat() == catSub)
458 else if (t.cat() == catParameter) {
459 Token const & n = p.getToken();
460 os << wrap("macroarg", string(1, n.character()));
463 else if (t.cat() == catActive) {
464 if (t.character() == '~')
465 os << (curr_env() == "lyxcode" ? ' ' : '~');
470 else if (t.cat() == catBegin) {
471 if (mode == MATH_MODE)
477 else if (t.cat() == catEnd) {
478 if (flags & FLAG_BRACE_LAST)
480 if (mode == MATH_MODE)
486 else if (t.cat() == catAlign) {
487 if (mode == MATH_MODE)
493 else if (t.cs() == "tabularnewline") {
494 if (mode == MATH_MODE)
500 else if (t.character() == ']' && (flags & FLAG_BRACK_LAST)) {
501 //cerr << "finished reading option\n";
505 else if (t.cat() == catOther)
506 os << string(1, t.character());
508 else if (t.cat() == catComment) {
511 Token const & t = p.getToken();
512 if (t.cat() == catNewline)
516 //os << wrap("comment", s);
524 else if (t.cs() == "lyxlock")
527 else if (t.cs() == "newcommand" || t.cs() == "providecommand") {
528 string const name = p.verbatimItem();
529 string const opts = p.getArg('[', ']');
530 string const body = p.verbatimItem();
531 // only non-lyxspecific stuff
532 if (name != "\\noun " && name != "\\tabularnewline ") {
533 ostream & out = in_preamble ? h_preamble : os;
535 begin_inset(os, "FormulaMacro\n");
536 out << "\\" << t.cs() << "{" << name << "}";
538 out << "[" << opts << "]";
539 out << "{" << body << "}";
545 else if (t.cs() == "(") {
546 begin_inset(os, "Formula");
548 parse(p, os, FLAG_SIMPLE2, MATH_MODE);
553 else if (t.cs() == "[") {
554 begin_inset(os, "Formula");
556 parse(p, os, FLAG_EQUATION, MATH_MODE);
561 else if (t.cs() == "protect")
562 // ignore \\protect, will hopefully be re-added during output
565 else if (t.cs() == "begin") {
566 string const name = p.getArg('{', '}');
567 active_environments.push(name);
568 if (name == "document") {
570 parse(p, os, FLAG_END, mode);
571 } else if (name == "abstract") {
573 parse(p, os, FLAG_END, mode);
574 } else if (is_math_env(name)) {
575 begin_inset(os, "Formula ");
576 os << "\\begin{" << name << "}";
577 parse(p, os, FLAG_END, MATH_MODE);
578 os << "\\end{" << name << "}";
580 } else if (name == "tabular") {
581 begin_inset(os, "Tabular \n");
582 string colopts = p.verbatimItem();
583 vector<string> colalign = extract_col_align(colopts);
585 parse(p, ss, FLAG_END, mode);
586 vector<string> lines;
587 split(ss.str(), lines, LINE);
588 const size_t cols = colalign.size();
589 const size_t rows = lines.size();
590 os << "<lyxtabular version=\"3\" rows=\"" << rows
591 << "\" columns=\"" << cols << "\">\n"
593 for (size_t c = 0; c < cols; ++c)
594 os << "<column alignment=\"" << colalign[c] << "\""
595 << " valignment=\"top\""
598 for (size_t r = 0; r < rows; ++r) {
599 vector<string> cells;
600 split(lines[r], cells, TAB);
601 while (cells.size() < cols)
602 cells.push_back(string());
603 //os << "<row bottomline=\"true\">\n";
605 for (size_t c = 0; c < cols; ++c) {
606 os << "<cell alignment=\"center\""
607 << " valignment=\"top\""
608 << " topline=\"true\""
609 << " leftline=\"true\""
610 << " usebox=\"none\""
612 begin_inset(os, "Text");
613 os << "\n\n\\layout Standard\n\n";
620 os << "</lyxtabular>\n";
622 } else if (name == "table") {
623 begin_inset(os, "Float table\n");
625 << "collapsed false\n"
627 << "\\layout Standard\n";
628 parse(p, os, FLAG_END, mode);
630 } else if (name == "thebibliography") {
631 p.verbatimItem(); // swallow next arg
632 parse(p, os, FLAG_END, mode);
633 os << "\n\\layout Standard\n\n";
634 } else if (mode == MATH_MODE) {
635 os << "\\begin{" << name << "}";
636 parse(p, os, FLAG_END, mode);
637 os << "\\end{" << name << "}";
639 parse(p, os, FLAG_END, mode);
643 else if (t.cs() == "end") {
644 if (flags & FLAG_END) {
645 // eat environment name
646 string const name = p.getArg('{', '}');
647 if (name != curr_env())
648 p.error("\\end{" + name + "} does not match \\begin{"
650 active_environments.pop();
653 p.error("found 'end' unexpectedly");
656 else if (t.cs() == "item")
659 else if (t.cs() == ")") {
660 if (flags & FLAG_SIMPLE2)
662 p.error("found '\\)' unexpectedly");
665 else if (t.cs() == "]") {
666 if (flags & FLAG_EQUATION)
668 p.error("found '\\]' unexpectedly");
671 else if (t.cs() == "documentclass") {
673 split(p.getArg('[', ']'), opts, ',');
674 handle_opt(opts, known_languages, h_language);
675 handle_opt(opts, known_fontsizes, h_paperfontsize);
676 h_quotes_language = h_language;
677 h_options = join(opts, ',');
678 h_textclass = p.getArg('{', '}');
681 else if (t.cs() == "usepackage") {
682 string const options = p.getArg('[', ']');
683 string const name = p.getArg('{', '}');
684 if (options.empty() && name.find(',')) {
685 vector<string> vecnames;
686 split(name, vecnames, ',');
687 vector<string>::const_iterator it = vecnames.begin();
688 vector<string>::const_iterator end = vecnames.end();
689 for (; it != end; ++it)
690 handle_package(trim(*it), string());
692 handle_package(name, options);
696 else if (t.cs() == "newenvironment") {
697 string const name = p.getArg('{', '}');
699 string const begin = p.verbatimItem();
701 string const end = p.verbatimItem();
703 if (name != "lyxcode")
704 os << wrap("newenvironment", begin + end);
707 else if (t.cs() == "def") {
708 string name = p.getToken().cs();
709 while (p.nextToken().cat() != catBegin)
710 name += p.getToken().asString();
711 handle_ert(os, "\\def\\" + name + '{' + p.verbatimItem() + '}');
714 else if (t.cs() == "setcounter") {
715 string const name = p.getArg('{', '}');
716 string const content = p.getArg('{', '}');
717 if (name == "secnumdepth")
718 h_secnumdepth = content;
719 else if (name == "tocdepth")
720 h_tocdepth = content;
722 h_preamble << "\\setcounter{" << name << "}{" << content << "}\n";
725 else if (t.cs() == "setlength") {
726 string const name = p.getToken().cs();
727 string const content = p.getArg('{', '}');
728 if (name == "parskip")
729 h_paragraph_separation = "skip";
730 else if (name == "parindent")
731 h_paragraph_separation = "skip";
733 h_preamble << "\\setlength{" << name << "}{" << content << "}\n";
736 else if (t.cs() == "par")
739 else if (is_heading(t.cs())) {
740 os << "\\layout " << cap(t.cs()) << "\n\n";
741 parse(p, os, FLAG_ITEM, mode);
744 else if (t.cs() == "makeindex" || t.cs() == "maketitle")
747 else if (t.cs() == "tableofcontents")
748 p.verbatimItem(); // swallow this
750 else if (t.cs() == "textrm") {
751 os << '\\' << t.cs() << '{';
752 parse(p, os, FLAG_ITEM, MATHTEXT_MODE);
756 else if ((t.cs() == "emph" || t.cs() == "noun") && mode == TEXT_MODE) {
757 os << "\n\\" << t.cs() << " on\n";
758 parse(p, os, FLAG_ITEM, mode);
759 os << "\n\\" << t.cs() << " default\n";
762 else if (is_latex_command(t.cs()) && mode == TEXT_MODE) {
763 begin_inset(os, "LatexCommand ");
764 os << '\\' << t.cs() << '{';
765 parse(p, os, FLAG_ITEM, TEXT_MODE);
770 else if (t.cs() == "bibitem") {
771 os << "\n\\layout Bibliography\n\\bibitem ";
772 string opt = p.getArg('[',']');
774 os << '[' << opt << ']';
775 os << '{' << p.getArg('{','}') << '}' << "\n\n";
778 else if (t.cs() == "textasciitilde")
781 else if (t.cs() == "_" && mode == TEXT_MODE)
784 else if (t.cs() == "&" && mode == TEXT_MODE)
788 if (mode == MATH_MODE)
790 else if (in_preamble)
791 h_preamble << t.asInput();
793 // heuristic: read up to next non-nested space
795 string s = t.asInput();
796 string z = p.verbatimItem();
797 while (p.good() && z != " " && z.size()) {
798 //cerr << "read: " << z << endl;
800 z = p.verbatimItem();
802 cerr << "found ERT: " << s << endl;
803 handle_ert(os, s + ' ');
805 handle_ert(os, t.asInput() + ' ');
809 if (flags & FLAG_LEAVE) {
810 flags &= ~FLAG_LEAVE;
818 } // anonymous namespace
821 int main(int argc, char * argv[])
824 cerr << "Usage: " << argv[0] << " <infile.tex>" << endl;
828 ifstream is(argv[1]);
830 parse(p, cout, 0, TEXT_MODE);
831 cout << "\n\\the_end";