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 void parse(Parser & p, ostream & os, unsigned flags, mode_type mode);
42 char const OPEN = '<';
43 char const CLOSE = '>';
45 // rather brutish way to code table structure in a string:
47 // \begin{tabular}{ccc}
49 // \multicolumn{2}{c}{4} & 5\\
53 // gets "translated" to:
56 // 2 MULT c MULT 4 TAB 5 LINE
59 char const TAB = '\001';
60 char const LINE = '\002';
61 char const MULT = '\003';
63 const char * known_languages[] = { "austrian", "babel", "bahasa", "basque",
64 "breton", "british", "bulgarian", "catalan", "croatian", "czech", "danish",
65 "dutch", "english", "esperanto", "estonian", "finnish", "francais",
66 "frenchb", "galician", "german", "germanb", "greek", "hebcal", "hebfont",
67 "hebrew", "hebrew_newcode", "hebrew_oldcode", "hebrew_p", "hyphen",
68 "icelandic", "irish", "italian", "latin", "lgrcmr", "lgrcmro", "lgrcmss",
69 "lgrcmtt", "lgrenc", "lgrlcmss", "lgrlcmtt", "lheclas", "lhecmr",
70 "lhecmss", "lhecmtt", "lhecrml", "lheenc", "lhefr", "lheredis", "lheshold",
71 "lheshscr", "lheshstk", "lsorbian", "magyar", "naustrian", "ngermanb",
72 "ngerman", "norsk", "polish", "portuges", "rlbabel", "romanian",
73 "russianb", "samin", "scottish", "serbian", "slovak", "slovene", "spanish",
74 "swedish", "turkish", "ukraineb", "usorbian", "welsh", 0};
76 char const * known_fontsizes[] = { "10pt", "11pt", "12pt", 0 };
78 char const * known_headings[] = { "caption", "title", "author",
79 "paragraph", "chapter", "section", "subsection", "subsubsection", 0 };
81 char const * known_math_envs[] = { "equation", "eqnarray", "eqnarray*",
82 "align", "align*", 0};
84 char const * known_latex_commands[] = { "ref", "cite", "label", "index",
87 // LaTeX names for quotes
88 char const * known_quotes[] = { "glqq", "grqq", 0};
90 // the same as known_quotes with .lyx names
91 char const * known_coded_quotes[] = { "gld", "grd", 0};
96 ostringstream h_preamble;
97 string h_textclass = "article";
98 string h_options = "";
99 string h_language = "english";
100 string h_inputencoding = "latin1";
101 string h_fontscheme = "default";
102 string h_graphics = "default";
103 string h_paperfontsize = "default";
104 string h_spacing = "single";
105 string h_papersize = "default";
106 string h_paperpackage = "default";
107 string h_use_geometry = "0";
108 string h_use_amsmath = "0";
109 string h_use_natbib = "0";
110 string h_use_numerical_citations = "0";
111 string h_paperorientation = "portrait";
112 string h_secnumdepth = "3";
113 string h_tocdepth = "3";
114 string h_paragraph_separation = "indent";
115 string h_defskip = "medskip";
116 string h_quotes_language = "english";
117 string h_quotes_times = "1";
118 string h_papercolumns = "1";
119 string h_papersides = "1";
120 string h_paperpagestyle = "default";
121 string h_tracking_changes = "0";
123 // indicates whether we are in the preamble
124 bool in_preamble = true;
126 // current stack of nested environments
127 stack<string> active_environments;
133 s[0] = toupper(s[0]);
138 string const trim(string const & a, char const * p = " ")
142 if (a.empty() || !*p)
145 string::size_type r = a.find_last_not_of(p);
146 string::size_type l = a.find_first_not_of(p);
148 // Is this the minimal test? (lgb)
149 if (r == string::npos && l == string::npos)
152 return a.substr(l, r - l + 1);
156 void split(string const & s, vector<string> & result, char delim)
160 while (getline(is, t, delim))
165 string join(vector<string> const & input, char delim)
168 for (size_t i = 0; i != input.size(); ++i) {
177 char const ** is_known(string const & str, char const ** what)
179 for ( ; *what; ++what)
186 void handle_opt(vector<string> & opts, char const ** what, string & target)
191 for ( ; *what; ++what) {
192 vector<string>::iterator it = find(opts.begin(), opts.end(), *what);
193 if (it != opts.end()) {
194 //cerr << "### found option '" << *what << "'\n";
203 bool is_math_env(string const & name)
205 for (char const ** what = known_math_envs; *what; ++what)
212 void begin_inset(ostream & os, string const & name)
214 os << "\n\\begin_inset " << name;
218 void end_inset(ostream & os)
220 os << "\n\\end_inset\n";
226 return active_environments.empty() ? string() : active_environments.top();
230 void handle_ert(ostream & os, string const & s)
232 begin_inset(os, "ERT");
233 os << "\nstatus Collapsed\n\n\\layout Standard\n\n";
234 for (string::const_iterator it = s.begin(), et = s.end(); it != et; ++it) {
236 os << "\n\\backslash\n";
244 void handle_par(ostream & os)
246 if (active_environments.empty())
249 string s = curr_env();
250 if (s == "document" || s == "table") {
251 os << "Standard\n\n";
254 if (s == "lyxcode") {
255 os << "LyX-Code\n\n";
258 os << cap(s) << "\n\n";
262 void handle_package(string const & name, string const & options)
264 //cerr << "handle_package: '" << name << "'\n";
265 if (name == "a4wide") {
266 h_papersize = "a4paper";
267 h_paperpackage = "widemarginsa4";
268 } else if (name == "ae")
270 else if (name == "aecompl")
272 else if (name == "amsmath")
274 else if (name == "amssymb")
276 else if (name == "babel")
278 else if (name == "fontenc")
280 else if (name == "inputenc")
281 h_inputencoding = options;
282 else if (name == "makeidx")
284 else if (name == "verbatim")
286 else if (is_known(name, known_languages)) {
288 h_quotes_language = name;
291 h_preamble << "\\usepackage[" << options << "]{" << name << "}\n";
293 h_preamble << "\\usepackage{" << name << "}\n";
298 vector<string> extract_col_align(string const & s)
301 for (size_t i = 0; i < s.size(); ++i) {
303 case 'c': res.push_back("center"); break;
304 case 'l': res.push_back("left"); break;
305 case 'r': res.push_back("right"); break;
306 default : res.push_back("right"); break;
313 void handle_tabular(Parser & p, ostream & os, mode_type mode)
315 begin_inset(os, "Tabular \n");
316 string colopts = p.verbatimItem();
317 vector<string> colalign = extract_col_align(colopts);
319 parse(p, ss, FLAG_END, mode);
320 vector<string> lines;
321 split(ss.str(), lines, LINE);
322 const size_t cols = colalign.size();
323 const size_t rows = lines.size();
324 os << "<lyxtabular version=\"3\" rows=\"" << rows
325 << "\" columns=\"" << cols << "\">\n"
327 for (size_t c = 0; c < cols; ++c)
328 os << "<column alignment=\"" << colalign[c] << "\""
329 << " valignment=\"top\""
332 for (size_t r = 0; r < rows; ++r) {
333 vector<string> cells;
334 split(lines[r], cells, TAB);
335 while (cells.size() < cols)
336 cells.push_back(string());
337 //os << "<row bottomline=\"true\">\n";
339 for (size_t c = 0; c < cols; ++c) {
341 string alignment = "center";
342 vector<string> parts;
343 split(cells[c], parts, MULT);
344 if (parts.size() > 2) {
345 os << " multicolumn=\"" << parts[0] << "\"";
346 alignment = parts[1];
348 os << " alignment=\"" << alignment << "\""
349 << " valignment=\"top\""
350 << " topline=\"true\""
351 << " leftline=\"true\""
352 << " usebox=\"none\""
354 begin_inset(os, "Text");
355 os << "\n\n\\layout Standard\n\n";
362 os << "</lyxtabular>\n";
367 string wrap(string const & cmd, string const & str)
369 return OPEN + cmd + ' ' + str + CLOSE;
373 void end_preamble(ostream & os)
376 os << "# tex2lyx 0.0.2 created this file\n"
377 << "\\lyxformat 222\n"
378 << "\\textclass " << h_textclass << "\n"
379 << "\\begin_preamble\n" << h_preamble.str() << "\n\\end_preamble\n"
380 << "\\options " << h_options << "\n"
381 << "\\language " << h_language << "\n"
382 << "\\inputencoding " << h_inputencoding << "\n"
383 << "\\fontscheme " << h_fontscheme << "\n"
384 << "\\graphics " << h_graphics << "\n"
385 << "\\paperfontsize " << h_paperfontsize << "\n"
386 << "\\spacing " << h_spacing << "\n"
387 << "\\papersize " << h_papersize << "\n"
388 << "\\paperpackage " << h_paperpackage << "\n"
389 << "\\use_geometry " << h_use_geometry << "\n"
390 << "\\use_amsmath " << h_use_amsmath << "\n"
391 << "\\use_natbib " << h_use_natbib << "\n"
392 << "\\use_numerical_citations " << h_use_numerical_citations << "\n"
393 << "\\paperorientation " << h_paperorientation << "\n"
394 << "\\secnumdepth " << h_secnumdepth << "\n"
395 << "\\tocdepth " << h_tocdepth << "\n"
396 << "\\paragraph_separation " << h_paragraph_separation << "\n"
397 << "\\defskip " << h_defskip << "\n"
398 << "\\quotes_language " << h_quotes_language << "\n"
399 << "\\quotes_times " << h_quotes_times << "\n"
400 << "\\papercolumns " << h_papercolumns << "\n"
401 << "\\papersides " << h_papersides << "\n"
402 << "\\paperpagestyle " << h_paperpagestyle << "\n"
403 << "\\tracking_changes " << h_tracking_changes << "\n";
407 void parse(Parser & p, ostream & os, unsigned flags, mode_type mode)
410 Token const & t = p.getToken();
413 cerr << "t: " << t << " flags: " << flags << "\n";
417 if (flags & FLAG_ITEM) {
418 if (t.cat() == catSpace)
422 if (t.cat() == catBegin) {
423 // skip the brace and collect everything to the next matching
425 flags |= FLAG_BRACE_LAST;
429 // handle only this single token, leave the loop if done
434 if (flags & FLAG_BRACED) {
435 if (t.cat() == catSpace)
438 if (t.cat() != catBegin) {
439 p.error("opening brace expected");
443 // skip the brace and collect everything to the next matching
445 flags = FLAG_BRACE_LAST;
449 if (flags & FLAG_OPTION) {
450 if (t.cat() == catOther && t.character() == '[') {
451 parse(p, os, FLAG_BRACK_LAST, mode);
453 // no option found, put back token and we are done
462 if (t.cat() == catMath) {
463 if (mode == TEXT_MODE || mode == MATHTEXT_MODE) {
464 // we are inside some text mode thingy, so opening new math is allowed
465 if (mode == TEXT_MODE)
466 begin_inset(os, "Formula ");
467 Token const & n = p.getToken();
468 if (n.cat() == catMath) {
469 // TeX's $$...$$ syntax for displayed math
471 parse(p, os, FLAG_SIMPLE, MATH_MODE);
473 p.getToken(); // skip the second '$' token
475 // simple $...$ stuff
478 parse(p, os, FLAG_SIMPLE, MATH_MODE);
481 if (mode == TEXT_MODE)
485 else if (flags & FLAG_SIMPLE) {
486 // this is the end of the formula
491 cerr << "mode: " << mode << endl;
492 p.error("something strange in the parser\n");
497 else if (t.cat() == catLetter)
500 else if (t.cat() == catSpace)
503 else if (t.cat() == catNewline)
506 else if (t.cat() == catSuper)
509 else if (t.cat() == catSub)
512 else if (t.cat() == catParameter) {
513 Token const & n = p.getToken();
514 os << wrap("macroarg", string(1, n.character()));
517 else if (t.cat() == catActive) {
518 if (t.character() == '~')
519 os << (curr_env() == "lyxcode" ? ' ' : '~');
524 else if (t.cat() == catBegin) {
525 if (mode == MATH_MODE)
531 else if (t.cat() == catEnd) {
532 if (flags & FLAG_BRACE_LAST)
534 if (mode == MATH_MODE)
540 else if (t.cat() == catAlign) {
541 if (mode == MATH_MODE)
547 else if (t.cs() == "tabularnewline") {
548 if (mode == MATH_MODE)
554 else if (t.cs() == "\\" && mode == MATH_MODE)
557 else if (t.cs() == "\\" && curr_env() == "tabular")
560 else if (t.character() == ']' && (flags & FLAG_BRACK_LAST)) {
561 //cerr << "finished reading option\n";
565 else if (t.cat() == catOther)
566 os << string(1, t.character());
568 else if (t.cat() == catComment) {
571 Token const & t = p.getToken();
572 if (t.cat() == catNewline)
576 //os << wrap("comment", s);
584 else if (t.cs() == "lyxlock")
587 else if (t.cs() == "newcommand" || t.cs() == "providecommand") {
588 string const name = p.verbatimItem();
589 string const opts = p.getArg('[', ']');
590 string const body = p.verbatimItem();
591 // only non-lyxspecific stuff
592 if (name != "\\noun " && name != "\\tabularnewline ") {
593 ostream & out = in_preamble ? h_preamble : os;
595 begin_inset(os, "FormulaMacro\n");
596 out << "\\" << t.cs() << "{" << name << "}";
598 out << "[" << opts << "]";
599 out << "{" << body << "}";
605 else if (t.cs() == "(") {
606 begin_inset(os, "Formula");
608 parse(p, os, FLAG_SIMPLE2, MATH_MODE);
613 else if (t.cs() == "[") {
614 begin_inset(os, "Formula");
616 parse(p, os, FLAG_EQUATION, MATH_MODE);
621 else if (t.cs() == "protect")
622 // ignore \\protect, will hopefully be re-added during output
625 else if (t.cs() == "begin") {
626 string const name = p.getArg('{', '}');
627 active_environments.push(name);
628 if (name == "document") {
630 parse(p, os, FLAG_END, mode);
631 } else if (name == "abstract") {
633 parse(p, os, FLAG_END, mode);
634 } else if (is_math_env(name)) {
635 begin_inset(os, "Formula ");
636 os << "\\begin{" << name << "}";
637 parse(p, os, FLAG_END, MATH_MODE);
638 os << "\\end{" << name << "}";
640 } else if (name == "tabular") {
641 handle_tabular(p, os, mode);
642 } else if (name == "table") {
643 begin_inset(os, "Float table\n");
645 << "collapsed false\n"
647 << "\\layout Standard\n";
648 parse(p, os, FLAG_END, mode);
650 } else if (name == "thebibliography") {
651 p.verbatimItem(); // swallow next arg
652 parse(p, os, FLAG_END, mode);
653 os << "\n\\layout Standard\n\n";
654 } else if (mode == MATH_MODE) {
655 os << "\\begin{" << name << "}";
656 parse(p, os, FLAG_END, mode);
657 os << "\\end{" << name << "}";
659 parse(p, os, FLAG_END, mode);
663 else if (t.cs() == "end") {
664 if (flags & FLAG_END) {
665 // eat environment name
666 string const name = p.getArg('{', '}');
667 if (name != curr_env())
668 p.error("\\end{" + name + "} does not match \\begin{"
670 active_environments.pop();
673 p.error("found 'end' unexpectedly");
677 else if (t.cs() == "item")
680 else if (t.cs() == ")") {
681 if (flags & FLAG_SIMPLE2)
683 p.error("found '\\)' unexpectedly");
686 else if (t.cs() == "]") {
687 if (flags & FLAG_EQUATION)
689 p.error("found '\\]' unexpectedly");
692 else if (t.cs() == "documentclass") {
694 split(p.getArg('[', ']'), opts, ',');
695 handle_opt(opts, known_languages, h_language);
696 handle_opt(opts, known_fontsizes, h_paperfontsize);
697 h_quotes_language = h_language;
698 h_options = join(opts, ',');
699 h_textclass = p.getArg('{', '}');
702 else if (t.cs() == "usepackage") {
703 string const options = p.getArg('[', ']');
704 string const name = p.getArg('{', '}');
705 if (options.empty() && name.find(',')) {
706 vector<string> vecnames;
707 split(name, vecnames, ',');
708 vector<string>::const_iterator it = vecnames.begin();
709 vector<string>::const_iterator end = vecnames.end();
710 for (; it != end; ++it)
711 handle_package(trim(*it), string());
713 handle_package(name, options);
717 else if (t.cs() == "newenvironment") {
718 string const name = p.getArg('{', '}');
720 string const begin = p.verbatimItem();
722 string const end = p.verbatimItem();
724 if (name != "lyxcode")
725 os << wrap("newenvironment", begin + end);
728 else if (t.cs() == "def") {
729 string name = p.getToken().cs();
730 while (p.nextToken().cat() != catBegin)
731 name += p.getToken().asString();
732 handle_ert(os, "\\def\\" + name + '{' + p.verbatimItem() + '}');
735 else if (t.cs() == "setcounter") {
736 string const name = p.getArg('{', '}');
737 string const content = p.getArg('{', '}');
738 if (name == "secnumdepth")
739 h_secnumdepth = content;
740 else if (name == "tocdepth")
741 h_tocdepth = content;
743 h_preamble << "\\setcounter{" << name << "}{" << content << "}\n";
746 else if (t.cs() == "setlength") {
747 string const name = p.getToken().cs();
748 string const content = p.getArg('{', '}');
749 if (name == "parskip")
750 h_paragraph_separation = "skip";
751 else if (name == "parindent")
752 h_paragraph_separation = "skip";
754 h_preamble << "\\setlength{" << name << "}{" << content << "}\n";
757 else if (t.cs() == "par")
760 else if (is_known(t.cs(), known_headings)) {
761 string name = t.cs();
762 if (p.nextToken().asInput() == "*") {
766 os << "\\layout " << cap(name) << "\n\n";
767 parse(p, os, FLAG_ITEM, mode);
770 else if (t.cs() == "makeindex" || t.cs() == "maketitle")
773 else if (t.cs() == "tableofcontents")
774 p.verbatimItem(); // swallow this
776 else if (t.cs() == "multicolumn" && mode == TEXT_MODE) {
778 parse(p, os, FLAG_ITEM, mode);
780 parse(p, os, FLAG_ITEM, mode);
782 parse(p, os, FLAG_ITEM, mode);
785 else if (t.cs() == "textrm") {
786 os << '\\' << t.cs() << '{';
787 parse(p, os, FLAG_ITEM, MATHTEXT_MODE);
791 else if ((t.cs() == "emph" || t.cs() == "noun") && mode == TEXT_MODE) {
792 os << "\n\\" << t.cs() << " on\n";
793 parse(p, os, FLAG_ITEM, mode);
794 os << "\n\\" << t.cs() << " default\n";
797 else if (is_known(t.cs(), known_latex_commands) && mode == TEXT_MODE) {
798 begin_inset(os, "LatexCommand ");
799 os << '\\' << t.cs() << '{';
800 parse(p, os, FLAG_ITEM, TEXT_MODE);
805 else if (t.cs() == "bibitem") {
806 os << "\n\\layout Bibliography\n\\bibitem ";
807 string opt = p.getArg('[',']');
809 os << '[' << opt << ']';
810 os << '{' << p.getArg('{','}') << '}' << "\n\n";
813 else if (char const ** where = is_known(t.cs(), known_quotes)) {
814 begin_inset(os, "Quotes ");
815 os << known_coded_quotes[where - known_quotes];
819 else if (t.cs() == "textasciitilde")
822 else if (t.cs() == "_" && mode == TEXT_MODE)
825 else if (t.cs() == "&" && mode == TEXT_MODE)
828 else if (t.cs() == "pagestyle" && in_preamble)
829 h_paperpagestyle == p.getArg('{','}');
832 if (mode == MATH_MODE)
834 else if (in_preamble)
835 h_preamble << t.asInput();
837 // heuristic: read up to next non-nested space
839 string s = t.asInput();
840 string z = p.verbatimItem();
841 while (p.good() && z != " " && z.size()) {
842 //cerr << "read: " << z << endl;
844 z = p.verbatimItem();
846 cerr << "found ERT: " << s << endl;
847 handle_ert(os, s + ' ');
849 handle_ert(os, t.asInput() + ' ');
853 if (flags & FLAG_LEAVE) {
854 flags &= ~FLAG_LEAVE;
862 } // anonymous namespace
865 int main(int argc, char * argv[])
868 cerr << "Usage: " << argv[0] << " <infile.tex>" << endl;
872 ifstream is(argv[1]);
874 parse(p, cout, 0, TEXT_MODE);
875 cout << "\n\\the_end";