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", "date",
79 "paragraph", "chapter", "section", "subsection", "subsubsection", 0 };
81 char const * known_math_envs[] = { "equation", "equation*",
82 "eqnarray", "eqnarray*", "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\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_tex(ostream & os, string const & s)
246 //os << "handle_tex(" << s << ")\n";
254 void handle_par(ostream & os)
256 if (active_environments.empty())
259 string s = curr_env();
260 if (s == "document" || s == "table") {
261 os << "Standard\n\n";
264 if (s == "lyxcode") {
265 os << "LyX-Code\n\n";
268 os << cap(s) << "\n\n";
272 void handle_package(string const & name, string const & options)
274 //cerr << "handle_package: '" << name << "'\n";
275 if (name == "a4wide") {
276 h_papersize = "a4paper";
277 h_paperpackage = "widemarginsa4";
278 } else if (name == "ae")
280 else if (name == "aecompl")
282 else if (name == "amsmath")
284 else if (name == "amssymb")
286 else if (name == "babel")
288 else if (name == "fontenc")
290 else if (name == "inputenc")
291 h_inputencoding = options;
292 else if (name == "makeidx")
294 else if (name == "verbatim")
296 else if (is_known(name, known_languages)) {
298 h_quotes_language = name;
301 h_preamble << "\\usepackage[" << options << "]{" << name << "}\n";
303 h_preamble << "\\usepackage{" << name << "}\n";
308 vector<string> extract_col_align(string const & s)
311 for (size_t i = 0; i < s.size(); ++i) {
313 case 'c': res.push_back("center"); break;
314 case 'l': res.push_back("left"); break;
315 case 'r': res.push_back("right"); break;
316 default : res.push_back("right"); break;
323 void handle_tabular(Parser & p, ostream & os, mode_type mode)
325 begin_inset(os, "Tabular \n");
326 string colopts = p.verbatimItem();
327 vector<string> colalign = extract_col_align(colopts);
329 parse(p, ss, FLAG_END, mode);
330 vector<string> lines;
331 split(ss.str(), lines, LINE);
332 const size_t cols = colalign.size();
333 const size_t rows = lines.size();
334 os << "<lyxtabular version=\"3\" rows=\"" << rows
335 << "\" columns=\"" << cols << "\">\n"
337 for (size_t c = 0; c < cols; ++c)
338 os << "<column alignment=\"" << colalign[c] << "\""
339 << " valignment=\"top\""
342 for (size_t r = 0; r < rows; ++r) {
343 vector<string> cells;
344 split(lines[r], cells, TAB);
345 while (cells.size() < cols)
346 cells.push_back(string());
347 //os << "<row bottomline=\"true\">\n";
349 for (size_t c = 0; c < cols; ++c) {
351 string alignment = "center";
352 vector<string> parts;
353 split(cells[c], parts, MULT);
354 if (parts.size() > 2) {
355 os << " multicolumn=\"" << parts[0] << "\"";
356 alignment = parts[1];
358 os << " alignment=\"" << alignment << "\""
359 << " valignment=\"top\""
360 << " topline=\"true\""
361 << " leftline=\"true\""
362 << " usebox=\"none\""
364 begin_inset(os, "Text");
365 os << "\n\n\\layout Standard\n\n";
373 os << "</lyxtabular>\n";
378 string wrap(string const & cmd, string const & str)
380 return OPEN + cmd + ' ' + str + CLOSE;
384 void end_preamble(ostream & os)
387 os << "# tex2lyx 0.0.2 created this file\n"
388 << "\\lyxformat 222\n"
389 << "\\textclass " << h_textclass << "\n"
390 << "\\begin_preamble\n" << h_preamble.str() << "\n\\end_preamble\n"
391 << "\\options " << h_options << "\n"
392 << "\\language " << h_language << "\n"
393 << "\\inputencoding " << h_inputencoding << "\n"
394 << "\\fontscheme " << h_fontscheme << "\n"
395 << "\\graphics " << h_graphics << "\n"
396 << "\\paperfontsize " << h_paperfontsize << "\n"
397 << "\\spacing " << h_spacing << "\n"
398 << "\\papersize " << h_papersize << "\n"
399 << "\\paperpackage " << h_paperpackage << "\n"
400 << "\\use_geometry " << h_use_geometry << "\n"
401 << "\\use_amsmath " << h_use_amsmath << "\n"
402 << "\\use_natbib " << h_use_natbib << "\n"
403 << "\\use_numerical_citations " << h_use_numerical_citations << "\n"
404 << "\\paperorientation " << h_paperorientation << "\n"
405 << "\\secnumdepth " << h_secnumdepth << "\n"
406 << "\\tocdepth " << h_tocdepth << "\n"
407 << "\\paragraph_separation " << h_paragraph_separation << "\n"
408 << "\\defskip " << h_defskip << "\n"
409 << "\\quotes_language " << h_quotes_language << "\n"
410 << "\\quotes_times " << h_quotes_times << "\n"
411 << "\\papercolumns " << h_papercolumns << "\n"
412 << "\\papersides " << h_papersides << "\n"
413 << "\\paperpagestyle " << h_paperpagestyle << "\n"
414 << "\\tracking_changes " << h_tracking_changes << "\n";
418 void parse(Parser & p, ostream & os, unsigned flags, mode_type mode)
421 Token const & t = p.getToken();
424 cerr << "t: " << t << " flags: " << flags << "\n";
428 if (flags & FLAG_ITEM) {
429 if (t.cat() == catSpace)
433 if (t.cat() == catBegin) {
434 // skip the brace and collect everything to the next matching
436 flags |= FLAG_BRACE_LAST;
440 // handle only this single token, leave the loop if done
445 if (flags & FLAG_BRACED) {
446 if (t.cat() == catSpace)
449 if (t.cat() != catBegin) {
450 p.error("opening brace expected");
454 // skip the brace and collect everything to the next matching
456 flags = FLAG_BRACE_LAST;
460 if (flags & FLAG_OPTION) {
461 if (t.cat() == catOther && t.character() == '[') {
462 parse(p, os, FLAG_BRACK_LAST, mode);
464 // no option found, put back token and we are done
473 if (t.cat() == catMath) {
474 if (mode == TEXT_MODE || mode == MATHTEXT_MODE) {
475 // we are inside some text mode thingy, so opening new math is allowed
476 if (mode == TEXT_MODE)
477 begin_inset(os, "Formula ");
478 Token const & n = p.getToken();
479 if (n.cat() == catMath) {
480 // TeX's $$...$$ syntax for displayed math
482 parse(p, os, FLAG_SIMPLE, MATH_MODE);
484 p.getToken(); // skip the second '$' token
486 // simple $...$ stuff
489 parse(p, os, FLAG_SIMPLE, MATH_MODE);
492 if (mode == TEXT_MODE)
496 else if (flags & FLAG_SIMPLE) {
497 // this is the end of the formula
502 cerr << "mode: " << mode << endl;
503 p.error("something strange in the parser\n");
508 else if (t.cat() == catLetter)
511 else if (t.cat() == catSpace)
514 else if (t.cat() == catNewline)
517 else if (t.cat() == catSuper)
520 else if (t.cat() == catSub)
523 else if (t.cat() == catParameter) {
524 Token const & n = p.getToken();
525 os << wrap("macroarg", string(1, n.character()));
528 else if (t.cat() == catActive) {
529 if (t.character() == '~')
530 os << (curr_env() == "lyxcode" ? ' ' : '~');
535 else if (t.cat() == catBegin) {
536 if (mode == MATH_MODE)
542 else if (t.cat() == catEnd) {
543 if (flags & FLAG_BRACE_LAST)
545 if (mode == MATH_MODE)
551 else if (t.cat() == catAlign) {
552 if (mode == MATH_MODE)
558 else if (t.cs() == "tabularnewline") {
559 if (mode == MATH_MODE)
565 else if (t.cs() == "\\" && mode == MATH_MODE)
568 else if (t.cs() == "\\" && curr_env() == "tabular")
571 else if (t.character() == ']' && (flags & FLAG_BRACK_LAST)) {
572 //cerr << "finished reading option\n";
576 else if (t.cat() == catOther)
577 os << string(1, t.character());
579 else if (t.cat() == catComment) {
582 Token const & t = p.getToken();
583 if (t.cat() == catNewline)
587 //os << wrap("comment", s);
595 else if (t.cs() == "lyxlock")
598 else if (t.cs() == "makeatletter") {
599 p.setCatCode('@', catLetter);
600 handle_tex(os, "\\makeatletter\n");
603 else if (t.cs() == "makeatother") {
604 p.setCatCode('@', catOther);
605 handle_tex(os, "\\makeatother\n");
608 else if (t.cs() == "newcommand" || t.cs() == "renewcommand"
609 || t.cs() == "providecommand") {
610 string const name = p.verbatimItem();
611 string const opts = p.getOpt();
612 string const body = p.verbatimItem();
613 // only non-lyxspecific stuff
614 if (name != "\\noun " && name != "\\tabularnewline ") {
615 ostream & out = in_preamble ? h_preamble : os;
617 begin_inset(os, "FormulaMacro\n");
618 out << "\\" << t.cs() << "{" << name << "}"
619 << opts << "{" << body << "}\n";
625 else if (t.cs() == "newtheorem") {
627 ss << "\\newtheorem";
628 ss << '{' << p.verbatimItem() << '}';
630 ss << '{' << p.verbatimItem() << '}';
633 handle_tex(os, ss.str());
636 else if (t.cs() == "(") {
637 begin_inset(os, "Formula");
639 parse(p, os, FLAG_SIMPLE2, MATH_MODE);
644 else if (t.cs() == "[") {
645 begin_inset(os, "Formula");
647 parse(p, os, FLAG_EQUATION, MATH_MODE);
652 else if (t.cs() == "protect")
653 // ignore \\protect, will hopefully be re-added during output
656 else if (t.cs() == "begin") {
657 string const name = p.getArg('{', '}');
658 active_environments.push(name);
659 if (name == "document") {
661 parse(p, os, FLAG_END, mode);
662 } else if (name == "abstract") {
664 parse(p, os, FLAG_END, mode);
665 } else if (is_math_env(name)) {
666 begin_inset(os, "Formula ");
667 os << "\\begin{" << name << "}";
668 parse(p, os, FLAG_END, MATH_MODE);
669 os << "\\end{" << name << "}";
671 } else if (name == "tabular") {
672 if (mode == TEXT_MODE)
673 handle_tabular(p, os, mode);
675 os << "\\begin{" << name << "}";
676 parse(p, os, FLAG_END, MATHTEXT_MODE);
677 os << "\\end{" << name << "}";
679 } else if (name == "table") {
680 begin_inset(os, "Float table\n");
682 << "collapsed false\n"
684 << "\\layout Standard\n";
685 parse(p, os, FLAG_END, mode);
687 } else if (name == "thebibliography") {
688 p.verbatimItem(); // swallow next arg
689 parse(p, os, FLAG_END, mode);
690 os << "\n\\layout Standard\n\n";
691 } else if (mode == MATH_MODE) {
692 os << "\\begin{" << name << "}";
693 parse(p, os, FLAG_END, mode);
694 os << "\\end{" << name << "}";
696 parse(p, os, FLAG_END, mode);
700 else if (t.cs() == "end") {
701 if (flags & FLAG_END) {
702 // eat environment name
703 string const name = p.getArg('{', '}');
704 if (name != curr_env())
705 p.error("\\end{" + name + "} does not match \\begin{"
707 active_environments.pop();
710 p.error("found 'end' unexpectedly");
714 else if (t.cs() == "item")
717 else if (t.cs() == ")") {
718 if (flags & FLAG_SIMPLE2)
720 p.error("found '\\)' unexpectedly");
723 else if (t.cs() == "]") {
724 if (flags & FLAG_EQUATION)
726 p.error("found '\\]' unexpectedly");
729 else if (t.cs() == "documentclass") {
731 split(p.getArg('[', ']'), opts, ',');
732 handle_opt(opts, known_languages, h_language);
733 handle_opt(opts, known_fontsizes, h_paperfontsize);
734 h_quotes_language = h_language;
735 h_options = join(opts, ',');
736 h_textclass = p.getArg('{', '}');
739 else if (t.cs() == "usepackage") {
740 string const options = p.getArg('[', ']');
741 string const name = p.getArg('{', '}');
742 if (options.empty() && name.find(',')) {
743 vector<string> vecnames;
744 split(name, vecnames, ',');
745 vector<string>::const_iterator it = vecnames.begin();
746 vector<string>::const_iterator end = vecnames.end();
747 for (; it != end; ++it)
748 handle_package(trim(*it), string());
750 handle_package(name, options);
754 else if (t.cs() == "newenvironment") {
755 string const name = p.getArg('{', '}');
756 if (name != "lyxcode") {
758 ss << "\\newenvironment{" << name << "}";
761 ss << '{' << p.verbatimItem() << '}';
762 ss << '{' << p.verbatimItem() << '}';
764 handle_tex(os, ss.str());
768 else if (t.cs() == "newfont") {
771 ss << '{' << p.verbatimItem() << '}';
772 ss << '{' << p.verbatimItem() << '}';
774 handle_tex(os, ss.str());
777 else if (t.cs() == "newcounter") {
779 ss << "\\newcounter";
780 ss << '{' << p.verbatimItem() << '}';
783 handle_tex(os, ss.str());
786 else if (t.cs() == "def") {
787 string name = p.getToken().cs();
788 while (p.nextToken().cat() != catBegin)
789 name += p.getToken().asString();
790 handle_ert(os, "\\def\\" + name + '{' + p.verbatimItem() + '}');
793 else if (t.cs() == "setcounter") {
794 string const name = p.getArg('{', '}');
795 string const content = p.getArg('{', '}');
796 if (name == "secnumdepth")
797 h_secnumdepth = content;
798 else if (name == "tocdepth")
799 h_tocdepth = content;
801 h_preamble << "\\setcounter{" << name << "}{" << content << "}\n";
804 else if (t.cs() == "setlength") {
805 string const name = p.verbatimItem();
806 string const content = p.verbatimItem();
807 if (in_preamble && name == "parskip")
808 h_paragraph_separation = "skip";
809 else if (in_preamble && name == "parindent")
810 h_paragraph_separation = "skip";
812 handle_tex(os, "\\setlength{" + name + "}{" + content + "}\n");
815 else if (t.cs() == "par")
818 else if (is_known(t.cs(), known_headings)) {
819 string name = t.cs();
820 if (p.nextToken().asInput() == "*") {
824 os << "\n\n\\layout " << cap(name) << "\n\n";
825 parse(p, os, FLAG_ITEM, mode);
828 else if (t.cs() == "makeindex" || t.cs() == "maketitle")
831 else if (t.cs() == "tableofcontents")
832 p.verbatimItem(); // swallow this
834 else if (t.cs() == "multicolumn" && mode == TEXT_MODE) {
836 parse(p, os, FLAG_ITEM, mode);
838 parse(p, os, FLAG_ITEM, mode);
840 parse(p, os, FLAG_ITEM, mode);
843 else if (t.cs() == "textrm") {
844 os << '\\' << t.cs() << '{';
845 parse(p, os, FLAG_ITEM, MATHTEXT_MODE);
849 else if ((t.cs() == "emph" || t.cs() == "noun") && mode == TEXT_MODE) {
850 os << "\n\\" << t.cs() << " on\n";
851 parse(p, os, FLAG_ITEM, mode);
852 os << "\n\\" << t.cs() << " default\n";
855 else if (is_known(t.cs(), known_latex_commands) && mode == TEXT_MODE) {
856 begin_inset(os, "LatexCommand ");
857 os << '\\' << t.cs() << '{';
858 parse(p, os, FLAG_ITEM, TEXT_MODE);
863 else if (t.cs() == "bibitem") {
864 os << "\n\\layout Bibliography\n\\bibitem ";
865 string opt = p.getArg('[',']');
867 os << '[' << opt << ']';
868 os << '{' << p.getArg('{','}') << '}' << "\n\n";
871 else if (char const ** where = is_known(t.cs(), known_quotes)) {
872 begin_inset(os, "Quotes ");
873 os << known_coded_quotes[where - known_quotes];
877 else if (t.cs() == "textasciitilde")
880 else if (t.cs() == "_" && mode == TEXT_MODE)
883 else if (t.cs() == "&" && mode == TEXT_MODE)
886 else if (t.cs() == "input")
887 handle_tex(os, "\\input{" + p.verbatimItem() + "}\n");
889 else if (t.cs() == "pagestyle" && in_preamble)
890 h_paperpagestyle == p.getArg('{','}');
892 else if (t.cs() == "fancyhead") {
896 ss << '{' << p.verbatimItem() << "}\n";
897 handle_tex(os, ss.str());
901 if (mode == MATH_MODE)
903 else if (in_preamble)
904 h_preamble << t.asInput();
906 // heuristic: read up to next non-nested space
908 string s = t.asInput();
909 string z = p.verbatimItem();
910 while (p.good() && z != " " && z.size()) {
911 //cerr << "read: " << z << endl;
913 z = p.verbatimItem();
915 cerr << "found ERT: " << s << endl;
916 handle_ert(os, s + ' ');
918 handle_ert(os, t.asInput() + ' ');
922 if (flags & FLAG_LEAVE) {
923 flags &= ~FLAG_LEAVE;
931 } // anonymous namespace
934 int main(int argc, char * argv[])
937 cerr << "Usage: " << argv[0] << " <infile.tex>" << endl;
941 ifstream is(argv[1]);
943 parse(p, cout, 0, TEXT_MODE);
944 cout << "\n\\the_end";